Saturday, April 28, 2012

Auto Refresh ASP.NET PAGE on Database Update

This is the aspx page source. The controls that you want to update must be inside the UpdatePanel. 


<body> 
<form id="form1" runat="server"> 
<asp:ScriptManager ID="ScriptManager1" runat="server"> 
</asp:ScriptManager> 
<div style="height: 804px; position: relative; top: 0px; left: 0px;" 
align="center"> 
<asp:UpdatePanel ID="UpdatePanel2" runat="server"> 
<ContentTemplate> 

<table style="width:100%; height: 100px;" width="50"> 

<tr> 
<td align="center" valign="top"> 
<asp:Label ID="lblUpdateTime" runat="server" Text="Label"></asp:Label> 
</td> 
</tr> 

<tr> 
<td align="center" valign="top"> 
<asp:Timer ID="Timer1" runat="server" Interval="10000" ontick="Timer1_Tick"> 
</asp:Timer> 
<asp:DataList ID="dlDataList" runat="server" CellPadding="2" 
GridLines="Vertical" Height="106px" RepeatColumns="1" Width="230px" 
BackColor="#0066CC"> 
<ItemTemplate> 
<asp:Label ID="MyTableField" runat="server" Font-Size="12pt" 
ForeColor="White" Text='<%# Eval("FieldBoundToList") %>' /> 
<br /> 
</ItemTemplate> 
<SeparatorStyle BorderColor="White" BorderWidth="2" Font-Size="Medium" /> 
</asp:DataList> 
</td> 
</tr> 

</table> 

</ContentTemplate> 

</asp:UpdatePanel> 

</div> 
</form> 
</body> 

And this is the code behind. 

protected void Timer1_Tick(object sender, EventArgs e) 


string ConnString = "Data Source=TEST\\SQLInstanceName;Initial Catalog=DatabaseName;Integrated Security=True"; 

try 

lblUpdateTime.Text = "Last Update: " + DateTime.Now.ToString(); 

//I am using LINQ To SQL here 
using (DataDataContext context = new DataDataContext(ConnString)) 

//Here I am using a stored procedure and binding the results to the datalist. 
//dlDataList.DataSource = context.spGetSomething().Take(20); 
//dlDataList.DataBind(); 

//Or you can do something like this. 
var query = from p in context.TableName 
select p; 

dlDataList.DataSource = query; 
dlDataList.DataBind(); 



catch (Exception) 


//Do something here 


No comments:

Post a Comment