Wednesday, March 21, 2012

Problem in Reloadind a GridView using Timer

Hi,

Iam new to ASP.net. I have a problem; I need to reload a gridview forevery five seconds. So, I am using a timer control. In thetimerconrol_elapsed event, I am getting the datasource from thedatabase and binding it into the gridview. The problem is, theretrieved data from th database is not displaying in the gridview. Hereis my code,

Default.aspx:

<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<atlas:ScriptManager EnablePartialRendering="true" ID="UpdateManager" runat="server"></atlas:ScriptManager>
<form id="form1" runat="server">
<div>

<atlas:UpdatePanel ID="upCityPanel" runat="server" Mode="Conditional">
<ContentTemplate>
<asp:GridView ID="GrdCity" runat="server" PageSize="5"></asp:GridView>
</ContentTemplate>
<Triggers>
<atlas:ControlEventTrigger ControlID="btn" EventName="Click" />
</Triggers>
</atlas:UpdatePanel>
<asp:Button runat="server" ID="btnReload" Text="Click to Reload" OnClick="ReloadGrid" />
</div>
</form>
</body>
</html
Default.aspx.cs:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Timers;

public partial class _Default : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection("server=localhost/;database=new;user id=sa;password=;");

protected void Page_Load(object sender, EventArgs e)
{
Timer timer = new Timer();
timer.Enabled = true;
timer.Interval = 5000;
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
}

void timer_Elapsed(object sender, ElapsedEventArgs e)
{
ReloadGrid(this, EventArgs.Empty);
}

protected void ReloadGrid(object sender, EventArgs e)
{
SqlDataAdapter da = new SqlDataAdapter("select distinct(city) from authors", conn);
DataTable dt = new DataTable();
if (dt != null)
da.Fill(dt);
GrdCity.DataSource = dt;
GrdCity.DataBind();
}

}

Can anyone tell me what should I need to do? for getting the proper output.

Thanks in advance.

UdhayaOk, everything looks good but using a System.Timer, you need to use an AJax timer, just drag and drop from the toolbox INSIDE the UpdatePanel and everything is going to work great!
Thanks a lot Albert, it's working fine now. Thanks for your reply :-)

No worries, glad I can help.

Please make sure you mark my post as answered so other people having the same problem can find the solution.

No comments:

Post a Comment