I am trying to display a basic clock from system time. I don't understand why this is crashing. I am hoping someone can help me to understand my error here.
At this point the form is just a label with short time displayed. I am trying to just make it update the label text on its own.
The label shows the time just fine on load. But when the timer_elapsed occurs the error is thrown
private void Form1_Load(object sender, EventArgs e)
{
lblClock.Text = DateTime.Now.ToShortTimeString();
timer = new System.Timers.Timer();
timer.Interval = 1000;
timer.Elapsed += timer_Elapsed;
timer.Enabled = true;
timer.Start();
}
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
lblClock.Text = DateTime.Now.ToShortTimeString();
}
The error is InvalidOperationException was unhandled by user code
Why does this work on load but not on update?
This was marked as a duplicate, but I have to disagree. Based on the linked duplicate thread the questions aren't the same. This question refers to why the exact same method works on load but not on call. The other thread is simply asking in general how to update a UI.