Friday, October 9, 2009

How to Add Auto Refresh Functionality to Web Application

Now in order to add auto refresh functionality for a gridview or in order to reload your session variables you can follow this following step.
Following example shows how you can add the auto refresh functionality to your Gridview:
For this you will require timer and Script manager need to be added in your code along with optional Update panel as shown below,


<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:Timer ID="Timer1" OnTick="Timer1_Tick" runat="server" Interval="30000">
</asp:Timer>
</div>
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Grid not refreshed yet."></asp:Label><br />
<asp:Label ID="Label4" runat="server" Text="(Grid Will Referesh after Every 30 Sec)"
Font-Bold="true"></asp:Label>
<br />
<br />
<asp:DataGrid ID="GridData" runat="server" Width="100%" HeaderStyle-BackColor="#999999"
AutoGenerateColumns="False">
<Columns>
<asp:BoundColumn DataField="Name" HeaderText="Employee ID"></asp:BoundColumn>
<asp:BoundColumn DataField="EffortsEstimated" HeaderText="First Name"></asp:BoundColumn>
<asp:BoundColumn DataField="EffortsRequired" HeaderText="Last Name"></asp:BoundColumn>
<asp:BoundColumn DataField="DefectsOpen" HeaderText="City"></asp:BoundColumn>
</Columns>
<HeaderStyle BackColor="#999999" />
</asp:DataGrid>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ProjectsDashboardConnectionString2 %>"
SelectCommand="SELECT [Name], [EffortsEstimated], [EffortsRequired], [DefectsOpen] FROM [Projects]">
</asp:SqlDataSource>
</ContentTemplate>
</asp:UpdatePanel>
</form>



In the .cs file i.e in the Code Behind file you have to include the following code which will be triggered by the timer after the specified interval( in this case 30 sec)


public void BindData()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ProjectsDashboardConnectionString2"].ConnectionString); SqlCommand cmd=new SqlCommand();
cmd.CommandText = "select * from Projects"; cmd.Connection = con; con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); cmd.ExecuteNonQuery(); GridData.DataSource = ds; GridData.DataBind();
}
protected void Timer1_Tick(object sender, EventArgs e)
{
Label1.Text = "Grid Refreshed at: " + DateTime.Now.ToLongTimeString(); this.BindData();
}

Now, after this run your code the application will refresh after every 30 sec...
Always find results on Fukat Ka Gyan !!! to save your time…

No comments:

Post a Comment