Timer控件更典型的应用是:定时刷新UpdatePanel控件的内容。
前台:
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="1000">
</asp:Timer>
<asp:Label ID="Label2" runat="server" Text="The time is:"></asp:Label>
<%= DateTime.Now.ToString("T") %><br />
</ContentTemplate>
</asp:UpdatePanel>
<br />
<fieldset>
<legend>
<asp:UpdatePanel ID="up1" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label ID="lblQuote" runat="server" Text="The time is:"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</legend>
</fieldset>
</div>
后台:
protected void Page_Load(object sender, EventArgs e)
{
List<string> quotes = new List<string>();
quotes.Add("A fool and his money are soon parted");
quotes.Add("A penny saved is a penny earned");
quotes.Add("An apple a day keeps the doctor away");
Random rnd = new Random();
lblQuote.Text = quotes[rnd.Next(quotes.Count)];
}
注:Timer控件每隔5秒刷新一次某论坛的信息。如果开着浏览器窗口,即使你去做别的事情,浏览器也能显示最新的信息,因为论坛上的其他人回传了这些内容。