I have this code:
bool on = true;
if (on == false)
{
on = true;
silenceToolStripMenuItem.Checked = false;
}
if (on == true)
{
on = false;
silenceToolStripMenuItem.Checked = true;
}
The first time you click it (by default it's unchecked) it will check itself. However, every time after that you check it it will not uncheck.
You forgot to write else part. Instead you wrote two if statements. So it was evaluating both and only second one was evaluated as the first always set on = true
.
Oh BTW, how about
bool on = true;
if (on == false)
{
on = true;
silenceToolStripMenuItem.Checked = false;
}
else
{
on = false;
silenceToolStripMenuItem.Checked = true;
}
Even more simple
bool on = true;
silenceToolStripMenuItem.Checked = on;
on = !on;
Because you are setting the local variable on
to true everytime it is never going to enter the if (on == false)
I think you want to make sure the on
is declatred ouside of the logic, and add the else stament so it does not change back.
private bool on = true:
private void MyMethod()
{
if (on == false)
{
on = true;
silenceToolStripMenuItem.Checked = false;
}
else if (on == true)
{
on = false;
silenceToolStripMenuItem.Checked = true;
}
}
or simply
private void MyMethod()
{
silenceToolStripMenuItem.Checked = !silenceToolStripMenuItem.Checked
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.