ASP.NET and AJAX: So Freaking Easy (Part 4: Timers)
Ever wondered how to add a timer to your ASP.NET application? Well, yeah, you guessed correctly again: so freaking easy. Two steps to adding a timer:
- Put the timer control on your page inside your <contenttemplate> tags.
- Set the Interval property of the timer to whatever span of time you want between partial-page post-backs (in milliseconds, ie: 1000 = 1 second)
That was too easy, you say. Okay, you want to do more? How about adding one timer to control multiple UpdatePanels? To do this, you will use a technique from my second post in this series about triggers. First, follow the steps above, except put your timer elsewhere on the page outside of your UpdatePanel. Next:
- In the UpdatePanels you want controlled by your timer, add an <asyncpostbacktrigger> to your <triggers> section, and specify the Timer control in the ID attribute (ie: <asyncpostbacktrigger id=”myTimerControl” />)
- Next, in that same trigger tag, add the attribute “eventname” and put in “Tick” as the value (ie: <asyncpostbacktrigger id=”myTimerControl” eventname=”Tick” />)
- Sit back and watch as all your UpdatePanels automatically update themselves.
If you really want to blow your mind, try adding several timers to your page that refresh at different intervals and linking them up to different UpdatePanels.
Seriously, so freaking easy, Microsoft. What happened to the days of making things challenging? KIDDING! KIDDING! Oh man, I’m sorry guys, I blew it for all of us.
EDIT: Remember, you can alter the behavior of the Timer control programmatically as well. For instance, to turn off the timer, you can create a button or checkbox or something that does: myTimer.Enabled = False. To alter the interval: myTimer.Interval = 60000 (or whatever).