I could have sworn I knew how to do this ... regardless, I want to check if a control matches the name of two other controls. If it matches either of the control's names, I want it to abort the "mission" if you will.
private void DisableMessageControls(Control myControl)
{
// if the control is checkbox3 OR panel7 I do NOT want to execute the below code!
if (myControl.Name != checkBox3.Name || myControl.Name != panel7.Name)
if (checkBox3.Checked == true)
{
myControl.Enabled = true;
}
else
{
myControl.Enabled = false;
}
foreach (Control myChild in myControl.Controls)
DisableMessageControls(myChild);
}开发者_如何学运维
You've got || combined with negative conditions. It's like saying, "If my name isn't Jon or it isn't Jeff." Well it can't be both, so that condition will always be true. I suspect you really want:
// Do you really need to check names instead of just references?
// You could probably just use
// if (myControl != checkBox3 && myControl != panel7)
if (myControl.Name != checkBox3.Name && myControl.Name != panel7.Name)
{
// No need for your if block here
myControl.Enabled = checkBox3.Checked;
}
I would also encourage you to always use braces, even for single-statement if
bodies - that makes it clearer that the foreach
isn't meant to be part of the if
body.
Your if statement will always return true
(assuming checkBox3 and panel7 have different names).
I think what you want is one of:
if (myControl.Name != checkBox3.Name && myControl.Name != panel7.Name)
or:
if (!(myControl.Name == checkBox3.Name || myControl.Name == panel7.Name))
reading it in english can help
what you have is:
if myControl.Name is not equal to checkbox3.name or is not equal to panel7.name
what you want is:
if myControl.Name is not equal to checkbox3.name or equal to panel7.name
if (!(myControl.Name == checkBox3.Name || myControl.Name == panel7.Name))
Here is what I ended up using:
private void DisableMessageControls(Control myControl)
{
if (myControl.Name == checkBox3.Name || myControl.Name == panel7.Name || myControl.Name == tpMessage.Name)
{
}
else
{
myControl.Enabled = checkBox3.Checked;
}
foreach (Control myChild in myControl.Controls)
DisableMessageControls(myChild);
}
精彩评论