user242375
user242375

Reputation: 691

GridView adds duplicate row on Page refresh

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

Upvotes: 0

Views: 3842

Answers (3)

Shakeeb Ahmed
Shakeeb Ahmed

Reputation: 1808

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.

Upvotes: 0

Tejinder Rai
Tejinder Rai

Reputation: 1

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.

Upvotes: 0

Nikos Steiakakis
Nikos Steiakakis

Reputation: 5745

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.

Upvotes: 5

Related Questions