Aarron Dixon
Aarron Dixon

Reputation: 97

How do I set an event to happen based on an exact time in c#

Working on hand crafting a binary clock for a class. I was just going to make some labels and have them switch colors based on the time. I was thinking for basic code for a label something like:

if (DateTime.Now.Hour = 1)
    lblHB1.BackColor = Color.Blue;
if (DateTime.Now.Hour = 3)
    lblHB1.BackColor = Color.Blue;
...
else
    lblHB1.BackColor = Color.Gray;

I've tried overcoming the errors myself but I'm getting nowhere.

I'm happy either knowing how to get this code to work, or being told about code that would accomplish the same thing.

Thanks!

Upvotes: 0

Views: 90

Answers (1)

Kamil Budziewski
Kamil Budziewski

Reputation: 23087

Change

if (DateTime.Now.Hour = 1)

to

if (DateTime.Now.Hour == 1)

You can not assign in an if statement, = is for assignment and == for comparing, look at Equality operator.

I suggest you to use if, else if, not bunch of if's, like:

var hour = DateTime.Now.Hour;

if(hour==1)
{
 ...
}
else if(hour==2)
{
  ...
}
...
else
{
 ...
}

with code above you will prevent calling 'else' when last if is not satisfied

Upvotes: 1

Related Questions