Create A Simple Dynamic Clock by Using UpdatePanel of ASP.NET AJAX
If you are developing web applications for different customer scenarios in which timestamping matters, there is a chance that you will be asked to put a real-time dynamic clock on the page depending on your real estate limitations on the UI. Any search result would give you several remedies to this purpose, but I wanted to have something short, neat and cross-browser compatible.
Here is the solution that I came up with by using an UpdatePanel and a few lines of JavaScript code.
First, create the UpdatePanel as in the following sample form:

OnLoad event of upDynamicClock will be handled in the server side:

Create a listener function (DisplayDynamicClock) by using the native setInterval function of JavaScript in order to update the content of lblDynamicClock and tell the page to run this function via window.onload:

Notice the usage of “__doPostBack” function as a bridge between JavaScript and ASP.NET for triggering a postback at upDynamicClock.
Conclusion
I have tested the outcome with the latest versions of IE and Firefox, and it worked fine with both of them:


Download
Sample code for this post can be found here.
Hey Mustafa - Your download link is not working.
It is fixed now. Thanks for pointing that out.
Great, but the screen flashes every second.
Probably, it is because you are using a content page (via master page) or a control (.ascx file). If that is the case, then you need to use <%=upDynamicClock.ClientID%> instead of upDynamicClock inside the __doPostBack function.
When the upDynamicClock’s DIV is created (while HMTL is rendered), its ID is set to something different than upDynamicClock due to being nested under a content page or a control. ClientID property would give you the right ID in every condition.
Hi.
The above code shows error message. I am working in C#. I think this code is only for VB.NET.
Regards,
- Balu
Yes, sample code is in VB.NET. For C#, simply change the server script as:
public void upDynamicClock_OnLoad(object sender, System.EventArgs e)
{
lblDynamicClock.Text = DateTime.Now.ToString;
}
Hello I use a Masterpage and in the function wrote
function DisplayDynamicClock(){
setInterval(”__doPostBack(’upDynamicClock.ClientID’, ”);”, 1000);
}
window.onload = DisplayDynamicClock;
but continue the flashes every second? Why?
Hi Silex,
You need to embrace the upDynamicClock.ClientID with server tags:
<%=upDynamicClock.ClientID%>
Thanks,
Regards from Russia.