Click here to Skip to main content
15,896,111 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
how to use timer??
i have a form and whenever it load the current time should display
and update itself automatically. i try to use the code below but its showing this error.
"Cross-thread operation not valid: Control 'label5' accessed from a thread other than the thread it was created on."
sorry for silly question but i m new to c#. :)
C#
private void start_form_Load_1(object sender, EventArgs e)
{
    System.Timers.Timer timerClock = new System.Timers.Timer();
    timerClock.Elapsed += new ElapsedEventHandler(OnTimer);
    timerClock.Interval = 1000;
    timerClock.Enabled = true;
}

public void OnTimer(Object source, ElapsedEventArgs e)
{
    label5.Text = DateTime.Now.ToString();
}


[Corrected some code formatting]
Posted
Updated 6-Mar-10 9:54am
v3

The previous answer you received is wrong.
You can do it in a very easy way.
You only need to use a System.Windows.Forms.Timer instead of your System.Timers.Timer.
That's All!

[Edit]
And, of course, the event should be Tick instead of OnTimer Elapsed.
 
Share this answer
 
v4
private void start_form_Load_1(object sender, EventArgs e)
{   
 System.Timers.Timer timerClock = new System.Timers.Timer();       
 timerClock.Elapsed += new ElapsedEventHandler(OnTimer);    
 timerClock.Interval = 1000;   
 timerClock.Enabled = true;
}
public void timer1_Tick(object sender, EventArgs e)
{   
 label5.Text = DateTime.Now.ToString();
}
 
Share this answer
 
v2
A timer runs on a separate thread. You cannot access a label property within the thread.

You need to use BeginInvoke. For a solution see here[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900