• How to refresh GridView automatically using AJAX Timer

    Posted on June 12, 2012 by in ASP.NET, C#, Dotnet

    AJAX Timer control enables a portion of an ASP.NET web page to be dynamically updated at a regular interval without the need of a user perform an action. When you add timer control to a page, a Javascript component is embedded in to the page. When the interval specified in the control elapses, this JS component initiates a postback to the server.  Please keep in mind that excessive use of Time controls can reduce the scalability of your application. Always use as high intervals as possible, and consider if contacting the server is really necessary or not.

    I am using Adventure Works provided by Microsoft as datasource. Open web.config and add following entry under connection strings element

    <add name="Sql" connectionString="Data Source={local};
    Initial Catalog= AdventureWorks;User=testuser;Password=testuser;" providerName="System.Data.SqlClient"/>
    

    Register the AjaxControlToolkit at the top of the page (or in the web.config for the whole project)

    <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

    The ScriptManager makes sure that the required ASP.NET AJAX files are included and that AJAX support is added, and has to be included on every page where you wish to use AJAX functionality.

    <asp:ScriptManager ID="ScriptManager1" runat="server" />

    In this example, we reload the GridView every every 30 seconds.  We have the Timer control outside the panel. Create an UpdatePanel control. Create a timer “ctlTimer” and place it outside the UpdatePanel. Since the timer is outside the panel, we need a trigger reference in the panel to this timer control. Add AsyncPostBackTrigger element to the UpdatePanel and set the ControlID property to this control so that Tick event can refresh the content of the panel.

    <html>
    <head runat="server">
        <title>Refresh Grid Example</title>
        <link type="text/css" rel="Stylesheet" href="../RefreshGridViewStyle.css" />       
    </head>
    <body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server"/>        
        <asp:Timer runat="server" ID="ctlTimer" 
                        Interval="30000" OnTick="OnTimerIntervalElapse" />         
        <asp:UpdatePanel runat="server" id="pnlUpdate">     
             <Triggers>
                 <asp:AsyncPostBackTrigger ControlID="ctlTimer" eventname="Tick"/>
            </Triggers>        
            <ContentTemplate>      
                <!—GridView & DataSource Content                             
            </ContentTemplate>
        </asp:UpdatePanel>    
    </form>
    </body>
    </html>
    

    I am using SQLDataSource to load the products from database. The ConnectionString property of the SqlDataSource control specifies how to connect to the database. This property can be a hard-coded connection string or can point to a connection string in a Web.config file as shown in the code given above. The SelectCommand property specifies the SQL statement to execute to retrieve the data.

    <asp:SqlDataSource ID="sqlDSProducts" runat="server" 
    ConnectionString="<%$ ConnectionStrings:Sql %>"
    SelectCommand="SELECT top 10 P.ProductID, P.Name, P.ProductNumber, P.ListPrice FROM Production.Product P                    
    ORDER BY P.ProductID desc">       
    </asp:SqlDataSource>
    

    We are interested in ProductID, ProductName, ProductNumber and LisPrice attributes of the product. I have added Bound  Columns to the GridView to render these attributes. In order to bind the SQLDataSource created above to the grid, set the “DataSourceID” property of the GridView to “sqlDSProducts” (ID property value of SQLDataSource).

    <asp:gridview ID="gvProducts"           
    AutoGenerateColumns="False" 
    runat="server" DataKeyNames="ProductID"               
    CssClass="GridViewStyle" DataSourceID="sqlDSProducts">          
    <RowStyle CssClass="RowStyle" />              
    <FooterStyle CssClass="RowStyle" />                        
    <SelectedRowStyle CssClass="SelectedRowStyle" />    
    <HeaderStyle CssClass="HeaderStyle" />              
    <AlternatingRowStyle CssClass="AltRowStyle" />
    <Columns>
        <asp:BoundField DataField="ProductID" HeaderText="Product ID"/>  
        <asp:BoundField DataField="ProductNumber" HeaderText="Product Number"/>  
        <asp:BoundField DataField="Name" HeaderText="Name"/>  
        <asp:BoundField DataField="ListPrice" HeaderText="Price" DataFormatString="{0:c}"/>
    </Columns>  
    </asp:gridview>
    

    In the OnTimerIntervalElapse event handler, we rebind the GridView so that sqlDSProducts control will make a call to database again to get products and the GridView will be rebounded with updated products list.

    protected void OnTimerIntervalElapse(object sender, EventArgs e)
    {
        gvProducts.DataBind();
    }
    

    Run the application and you would notice top 10 products are loaded onto the grid.

    Execute the following statement in database to update name of one of those products before 30 seconds elapse.

    Update Production.Product set Name = Name + ' --updated' where ProductID = 999

    After 30 seconds you would notice that grid is reloaded again and you would notice change in product name of one of the products.

    Complete Source Code:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>Timer Example</title>
        <link type="text/css" rel="Stylesheet" href="../RefreshGridViewStyle.css" />       
    </head>
    <body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server"/>        
        <asp:Timer runat="server" ID="ctlTimer" Interval="30000" OnTick="OnTimerIntervalElapse" />         
        <asp:UpdatePanel runat="server" id="pnlUpdate">     
             <Triggers>
                 <asp:AsyncPostBackTrigger ControlID="ctlTimer" eventname="Tick"/>
            </Triggers>        
            <ContentTemplate>      
                <asp:SqlDataSource ID="sqlDSProducts" runat="server" 
                    ConnectionString="<%$ ConnectionStrings:Sql %>"
                SelectCommand="SELECT top 10 P.ProductID, P.Name, P.ProductNumber, P.ListPrice 
    		            FROM Production.Product P ORDER BY P.ProductID desc">       
            </asp:SqlDataSource>      
            <asp:gridview ID="gvProducts"           
                AutoGenerateColumns="False" runat="server" DataKeyNames="ProductID"               
                CssClass="GridViewStyle" DataSourceID="sqlDSProducts">          
                <RowStyle CssClass="RowStyle" />              
                <FooterStyle CssClass="RowStyle" />                        
                <SelectedRowStyle CssClass="SelectedRowStyle" />    
                <HeaderStyle CssClass="HeaderStyle" />              
                <AlternatingRowStyle CssClass="AltRowStyle" />
                <Columns>
                    <asp:BoundField DataField="ProductID" HeaderText="Product ID"/>  
                    <asp:BoundField DataField="ProductNumber" HeaderText="Product Number"/>  
                    <asp:BoundField DataField="Name" HeaderText="Name"/>  
                    <asp:BoundField DataField="ListPrice" HeaderText="Price" DataFormatString="{0:c}"/>
                </Columns>  
            </asp:gridview>                                 
            </ContentTemplate>
        </asp:UpdatePanel>    
    </form>
    </body>
    </html>
    
    Be Sociable, Share!
      Post Tagged with , , ,

    Written by

    Software architect with over 10 years of proven experience in designing & developing n-tier and web based software applications, for Finance, Telecommunication, Manufacturing, Internet and other Commercial industries. He believes that success depends on one's ability to integrate multiple technologies to solve a simple as well as complicated problem.

    View all articles by

    Email : [email protected]