Sunday, February 20, 2011

Refresh the gridview without refreshing the whole page using Ajax in asp.net

To refresh particular control we have to use <asp:UpdatePanel> with <asp:Timer> Ajax control.

Before taking this control we have to take <asp:ScriptManager> 
in aspx page
 <asp:ScriptManager ID="ScriptManager1" runat="server">
 </asp:ScriptManager>
  <asp:UpdatePanel ID="UpdatePanel2" runat="server">
  <ContentTemplate>
        <asp:Timer ID="Timer1" runat="server" Interval="5000">
        </asp:Timer>
  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
       <Columns>
       <asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" />
       <asp:BoundField DataField="Message" HeaderText="Message"
                SortExpression="Message" />
       </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
        ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
        SelectCommand="SELECT [Date], [Message] FROM [ChatDb]"></asp:SqlDataSource>
    </ContentTemplate>
    <Triggers>
   <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
    </Triggers>
    </asp:UpdatePanel>
in .cs page

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = SqlDataSource1;
            GridView1.DataBind();
        }
    }
OR

 protected void Timer1_Tick(object sender, EventArgs e)
    {

            GridView1.DataSource = SqlDataSource1;
            GridView1.DataBind();

    }

No comments:

Post a Comment