Click here to Skip to main content
6,629,377 members and growing! (21,434 online)
Email Password   helpLost your password?
Web Development » ASP.NET Controls » General     Intermediate License: The GNU General Public License (GPL)

Creating Serverside Clock Control Using ASP.NET Ajax and C#

By blue_arc

Demonstration of Timer Control and updata panel to fire timed server events
C# (C# 1.0, C# 2.0, C# 3.0), .NET, WebForms, Dev
Version:3 (See All)
Posted:2 Jun 2008
Views:26,358
Bookmarked:20 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
6 votes for this article.
Popularity: 2.55 Rating: 3.27 out of 5
1 vote, 16.7%
1
1 vote, 16.7%
2
1 vote, 16.7%
3
1 vote, 16.7%
4
2 votes, 33.3%
5

Introduction

In this article, we will learn how to use Timer and Updatepanel controls of ASP.NET inside Custom Control to create other wrapper controls.

Prerequisite

To use this, you need to have atleast .NET Framework 2.0 and ASP.NET AJAX Extension Controls.

Background

Using Timer, we can repeat any set of commands on a timely basis. Using Update panel, we can process our request in asynchronous mode. So to demonstrate this, I will show you a simple Server Side Clock Control. Where I will put a set of instructions on Tick event of Timer, then will wrap it inside an Updatepanel. And at every second, the clock will refresh itself.

Assumptions

I am assuming that the reader of this article is aware about ASP.NET Ajax.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Ravs
{
    // Declare a clock class
    [ToolboxData("<{0}:Clock  runat="server">")]
    public class Clock : WebControl
    {
        //Create one TimerControl
        Timer timer = new Timer();
        // Create one label control for click value
        Label clockLabel = new Label();
        // Declare one Updatepanel
        UpdatePanel updatePanel = new UpdatePanel();
        // Now override the Load event of Current Web Control
        protected override void OnLoad(EventArgs e)
        {            
            // Create Ids for Control
            timer.ID = ID + "_tiker";
            clockLabel.ID = ID + "_l";
            // get the contentTemplate Control Instance
            Control controlContainer = updatePanel.ContentTemplateContainer;
            // add Label and timer control in Update Panel
            controlContainer.Controls.Add(clockLabel);
            controlContainer.Controls.Add(timer);
            // Add control Trigger in update panel on Tick Event
            updatePanel.Triggers.Add(new AsyncPostBackTrigger() 
		{ ControlID = timer.ID, EventName = "Tick" });
            updatePanel.ChildrenAsTriggers = true;
            // Set default clock time in label
            clockLabel.Text = DateTime.Now.ToString();
            // Set Interval
            timer.Interval = 1000;
            // Add handler to timer
            timer.Tick += new EventHandler(timer_Tick);

            updatePanel.RenderMode = UpdatePanelRenderMode.Block;
            //Add update panel to the base control collection.
            base.Controls.Add(updatePanel);
        }
        protected override void Render(HtmlTextWriter output)
        {
            base.Render(output);
        }

        void timer_Tick(object sender, EventArgs e)
        {
            // Set current date time in label to move current at each Tick Event
            clockLabel.Text = DateTime.Now.ToString();
        }
    }
}

Let’s Discuss Each Bit Individually

Up till now what we have seen. A little text and few lines of code fairly commented. So are you as a reader able to understand what I want to say. I think no. So now I have to come out of my laziness and discuss this with you in detail. So let's take each bit of code and examine what exactly it does.

Namespaces for Creating Control

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

We have inherited our Clock control from Webcontrol, so by default our control will contain all the properties and methods that WebControl contains.

[ToolboxData("<{0}:Clock  runat="server">")]
public class Clock : WebControl      

Control Initialization

To create this control, we need a control like Timer, Label, UpdatePanel.

  • Timer: will add auto fire functionality in control
  • Label: will be used to display clock data on web form
  • UpdatePanel: is used for converting the whole clock process in asynchronous mode, so that it will not refresh data of webform, and user will able to do his/her work, and clock will keep running. Sounds good :)
//Create one TimerControl
Timer timer = new Timer();
// Create one label control for click value
Label clockLabel = new Label();
// Declare one Updatepanel
UpdatePanel updatePanel = new UpdatePanel();
// Now override the Load event of Current Web Control

Binding of Controls

As you can see, we have created dynamic Id's of every control so that it should not create a problem when we use two timer controls on the same page.

protected override void OnLoad(EventArgs e)
        {            
            // Create Ids for Control
            timer.ID = ID + "_tiker";
            clockLabel.ID = ID + "_l";

Below you can see that I tried to get the ContentTemplateContainer in a control. Which is an instance of Internal Control with implementation of Itemplate where we will now add our controls.

// get the contentTemplate Control Instance
Control controlContainer = updatePanel.ContentTemplateContainer;
// add Label and timer control in Update Panel
controlContainer.Controls.Add(clockLabel);
controlContainer.Controls.Add(timer);

Now we have added all the controls (Timer and Label) in the updatepanel's contentpanel. So let's move to the main part. Now we will add timer control's reference in update panel’s control trigger with Event name "Tick", so that whenever Timer will raise its Tick event, Update panel will catch it and make it as an Asynchronous request. Now we will set the default data in our label. which is current DateTime, and we will set timer Interval property, (I am using static 1000, you can extend if you wish) so that Timer will know when it has to fire its tick event. Now the last thing we have to do is create an event for timer, so here it is.

timer.Tick += new EventHandler(timer_Tick); 

After that, add updatepanel into base control collection.

// Add control Trigger in update panel on Tick Event
updatePanel.Triggers.Add(new AsyncPostBackTrigger() 
{ 
ControlID = timer.ID, EventName = "Tick" });
updatePanel.ChildrenAsTriggers = true;
// Set default clock time in label
clockLabel.Text = DateTime.Now.ToString();
// Set Interval
timer.Interval = 1000;
// Add handler to timer
timer.Tick += new EventHandler(timer_Tick);

updatePanel.RenderMode = UpdatePanelRenderMode.Block;
//Add update panel to the base control collection.
base.Controls.Add(updatePanel);
}

Setting Logic on Tick Event

Here we don't have to do much. Just set the current date time value to label:

void timer_Tick(object sender, EventArgs e) 
{ 
    // Set current date time in label to move current at each Tick Event 
    clockLabel.Text = DateTime.Now.ToString(); 
} 

NOTE: There is no definition about Render method, as I have not done anything in this.

How To Use

Compile your control class and add it in Toolbox, and then drag it on the page. It will show you running clock without refreshing the page. I hope you will learn something from this, and may be you will come up with something more powerful.

Points of Interest

While developing this code, I got a few more good ideas using Timer and update panel. I will try my best to come back to you guys with something new as soon as possible.

History

  • 2nd June, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPL)

About the Author

blue_arc


Member
My Name is Ravi Kant Srivastava. Alias= ravs

I am an Indian lives in India.
I am a graduate in Economics, and a computer student from childhood. Professionally i am working as a Sr. Software Engg(mumbai).
In IT i am working from more than 4 years.
I personally like work on javascript and AJAX, Asp.net 2.0/3.5, WCF, WF, WPF, Silverlight - c#.
My hobbies are- palying cricket(i love it man).
good music, eating, solving complex algo's.

Occupation: Software Developer (Senior)
Company: Connexxions Business Support Services
Location: India India

Other popular ASP.NET Controls articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 1 of 1 (Total in Forum: 1) (Refresh)FirstPrevNext
GeneralCode error PinmemberJansen20823:43 28 Sep '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 2 Jun 2008
Editor: Deeksha Shenoy
Copyright 2008 by blue_arc
Everything else Copyright © CodeProject, 1999-2009
Web18 | Advertise on the Code Project