Why does this work?
private void button1_Click(object sender, EventArgs e)
{
if (!checkBox1.Checked)
{
MessageBox.Show("The box is not checked!");
}
if (checkBox1.Checked == true)
{
if (label1.BackColor == Color.Red)
{
label1.BackColor = Color.Blue;
}
else
{
label1.BackColor = Color.Red;
}
}
}
But this doesn't?
private void button1_Click(object sender, EventArgs e)
{
if (!checkBox1.Checked)
{
MessageBox.Show("The box is not checked!");
}
if (checkBox1.Checked == true)
{
if (label1.BackColor == Color.Red)
{
label1.BackColor = Color.Blue;
}
if (label1.BackColor == Color.Blue)
{
label1.BackColor = Color.Red;
}
}
}
I would think that the compliler would read the lines each time I press the button so it should not be any different to have two if statements after each other.
You are changing to blue if it was red and then your are changing it to red if it was blue. Basically first if first if
will change it to blue then second if
will change it back to red. It works this way because instructions are executed sequentially, so your second if
is always checked after your first if
. Just use else if
so second if
won't work if first one fired:
// if red then change to blue
if (label1.BackColor == Color.Red)
{
label1.BackColor = Color.Blue;
}
// otherwise, if blue then change to red
// this condition will be checked if first "if" was false
else if (label1.BackColor == Color.Blue)
{
label1.BackColor = Color.Red;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With