Search This Blog

Wednesday, December 22, 2010

Ajax to update GridView after certain interval using Asp.net C#

In most of the cases like Dashboard developers often need to update GridView data after certain interval. In this Asp.Net article i am going to discuss Updating GridView using AJAX. To do that first create a new aspx page in your project. Then drag and drop the below controls within the page.

1. ScriptManager
2. UpdatePanel
3. GridView
4. Timer



<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Updating GridView using AJAXtitle>
head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:ScriptManager ID="ScriptManager1" runat="server">asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
           
         <asp:GridView ID="GridView_Products" runat="server" AutoGenerateColumns="False"
            Width="100%" Font-Names="tahoma" >
        <HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
        <RowStyle BackColor="Gray" />
        <AlternatingRowStyle BackColor="LightGray" />
        <SelectedRowStyle BackColor="Pink" ForeColor="White" Font-Bold="true" />
        <Columns>
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="Description" HeaderText="Description" />
        <asp:BoundField DataField="Color" HeaderText="Color" />
        <asp:BoundField DataField="Size" HeaderText="Size" />
        <asp:CommandField ShowSelectButton="True" />
        Columns>
        asp:GridView>   
                <asp:Timer ID="Timer1" runat="server" ontick="Timer1_Tick">
                asp:Timer>
          ContentTemplate>

        asp:UpdatePanel>
    div>
    form>
body>
html>

Now right click on Timer control from design view. Click on event. Select Tick event and click twice to go to the code behind. Now within the Timer Tick event just bind the GridView data. Its automatically refresh the GridView after certain interval which you can mention in the Interval properties of the Timer control in seconds. The code sample is given below:

protected void Timer1_Tick(object sender, EventArgs e)
{
GridView_Products.DataSource = clsDbUtility.ExecuteQuery("Select * FROM Product");
GridView_Products.DataBind();
}
Now insert data from another page and check back your GridView that it has been refreshed. Hope it will help you.

1 comment:

Note: Only a member of this blog may post a comment.