0

GridView adds duplicate row on Page refresh--

I am having two methods 1)bindgridview() 2) insertdata()

whenever i am inserting the data through webform and displaying the data in gridview after that when i am refresshing page or press f5 again the duplicate record is inserted can anyone tell me what is the solution for this

where shall is if(!page.ispostback) in pageload event or insert data can anyone tell me,,

Thanx in advance

user242375
  • 691
  • 1
  • 6
  • 5

3 Answers3

5

A solution I used in the past was to add a time stamp to check if the Postback is a refresh. What I did was add

Page_Load()
{
    ...
    Session["CurrentTime"] = Server.UrlEncode(DateTime.Now.ToString());
}

and also on

protected override void OnPreRender(EventArgs e)
{
   ViewState["CurrentTime"] = Session["CurrentTime"];
}

then, when InsertData() was called, I would add a check like this

InsertData()
{
     if(ViewState["CurrentTime"].ToString() != Session["CurrentTime"].ToString())
         return;
}

EDIT: I looked up the code, and this is the correct way to make it work. Hope I've helped.

Nikos Steiakakis
  • 5,605
  • 7
  • 44
  • 54
0

if you call the function insertdata() in Page_Load without the condition of Postback it always run the function.

The better is call the insertdata() function on the button click event.

if the buttons is the child of gridview then you can use the RowCommand event of gridview to do this.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Shakeeb Ahmed
  • 1,778
  • 1
  • 21
  • 37
0

I have another way of doing the refresh. In your Page_Load() method, do the following:

GridViewname.Columns.Clear();

This worked for me, and also works well with AJAX enabled pages.

Ilia Ross
  • 13,086
  • 11
  • 53
  • 88