Date Time Windows Form User Control


User Control to display the current date & time on Windows form. Delagates, Timer and Evnets are used to display the current date and time.

Creating a Date & Time User Control
1.Create a Windows Application project.
2. Add a new User control and name it as DateTimeUserControl.cs
3. Add a label to the user control to display the date & time and name it as lblDisplayTime
4. Define a delegate and a timer control as private varibles.


#region private Variables
//Delegate to display the date and time
delegate void DisplayTime();
//timer to show the time for every second
System.Timers.Timer displayTimer = new System.Timers.Timer();

#endregion

5.Define an event for timer Elapsed.

public void DisplayTimeEvent(object source, ElapsedEventArgs e)
{
//Create a object for delegate
DisplayTime disp = new DisplayTime(ShowCurrentTime);
//invoke the delegate
this.BeginInvoke(disp);
}

6.Define a method to assign date time to the text property of the lblDisplayTime.

private void ShowCurrentTime()
{
lblDisplayTime.Text = DateTime.Now.ToString();
}

7. Now on user control load event add event elapsed event, set timer interval and start the timer to show the date time

private void DateTimeUserControl_Load(object sender, EventArgs e)
{
displayTimer.Elapsed += new ElapsedEventHandler(DisplayTimeEvent);
displayTimer.Interval = 1000;//set interval in milliseconds.
//Start the timer
displayTimer.Start();
}

8. Now build the project.
9. Add a form and darg and drop the DateTiemUserControl from Tool box.
10.Now run the project and able to see date & time on the form.

Find the attached sample project to test the above code.


Attachments

  • Date and Time User Control (38276-10229-Test.zip)
  • Related Articles

    More articles: Date time custom control User control date time Custom control User Control Timer Delegate

    Comments

    No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: