Force GridView to Refresh in ASP.NET

To force gridview to referesh in code, I have come across a couple of solutions, I will them all. The one that works best is to use databind() on gridview

GridView.DataBind(); /* this will referesh the gridview */

This is the most elegant solution. As an exmaple, lets say you have a GridView to that display data from a table. You have another FormView that inserts that into the gridview. If you insert the data, you will notice that gridview does not gets updated. To cure this, select the FormView, go to properties, create the IntemInserted event for the form and put this code in it

 protected void FormView2_ItemInserted(object sender, FormViewInsertedEventArgs e)
    {
        GridView1.DataBind();
    }

This will cause the gridview to refresh. As soon as you add the data, Gridview will automatically display it. In the background what actually happens is, .DataBind() forces page fresh. When page is reloaded, it reloads the new data while it maintains its present state. Everything is so fast you don’t seem to notice it.

Other Solutions

Some has commented that you have to call databind on both SQLDataSource and the gridview to refresh data as in follows

    sqlDataSource1.DataBind();
    GridView1.DataBind();

In my case I confirmed, binding on datasoruce is not needed at least in this case.

Yet another Solution

GridView1.DataBind();
GridView1.SelectedIndex = -1;

This was a problematic solution. It caused my delete in gridview not to work. Dont know why exactly was so, May be I put it in the wrong function but it did work fo refreshing the gridview.

One Response to Force GridView to Refresh in ASP.NET
  1. anita says:

    I was looking for this solution. I found it here. Thanks for the post. In my case I have a table with only one column which is date field. Its the primary key too.
    The first solution you mentioned is the best
    GridView.DataBind();

    Anita

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>