Timer controlTimer controls allow you to do postbacks at certain intervals. If used together with UpdatePanels, which is the most common approach, it allows for timed partial updates of your page, but it can be used for posting back the entire page as well. In this chapter we will focus on using timers with UpdatePanels, so if you haven't already read the chapter on UpdatePanels, please do so now.
Here is a small example of using the Timer control. It simply updates a timestamp every 5 seconds.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Timers</title> </head> <body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server" /> <asp:Timer runat="server" id="UpdateTimer" interval="5000" ontick="UpdateTimer_Tick" /> <asp:UpdatePanel runat="server" id="TimedPanel" updatemode="Conditional"> <Triggers> <asp:AsyncPostBackTrigger controlid="UpdateTimer" eventname="Tick" /> </Triggers> <ContentTemplate> <asp:Label runat="server" id="DateStampLabel" /> </ContentTemplate> </asp:UpdatePanel> </form> </body> </html>We only have a single CodeBehind function, which you should add to your CodeBehind file:
You should always remember that even though partial updates are not as heavy on the server as real postbacks, the server is still contacted, and when using timers, you may get a lot of partial postbacks, which can slow things down. Always use as high intervals as possible, and consider if contacting the server is really necessary or not.