Monday, August 17, 2009

How to refresh an ASP.NET GridView automatically at regular intervals

A common requirement is to refresh the GridView after regular intervals. ASP.NET contains the Timer control which comes in very handy to achieve such requirements. Here's how to do so:

Add the GridView and the Timer control inside an ASP.NET AJAX UpdatePanel as shown below :

<asp:UpdatePanel ID="UpdatePanel1" runat="server">


<ContentTemplate>


<asp:Timer ID="Timer1" runat="server" Interval="3600" ontick="Timer1_Tick">asp:Timer>


<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID"


DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True">


<Columns>


<asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" SortExpression="CustomerID" />


<asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />


<asp:BoundField DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName" />


<asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />


<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />


Columns>


asp:GridView>


ContentTemplate>


asp:UpdatePanel>


Then in the code behind, add the following code which refreshes the GridView after every minute

C#


protected void Timer1_Tick(object sender, EventArgs e)


{


GridView2.DataBind();


}




VB.NET


Protected Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs)


GridView2.DataBind()


End Sub



No comments:

Post a Comment