C # Forefront to change specific properties of an object?

I have a panel with checkboxes and shortcuts, I want to change all checked statuses of checkboxes when I click the button.

foreach (object x in panel1.Controls)
        {
            if (x.GetType() == typeof(CheckBox))
            {
                x.Checked = false; // problem is here;
                // (CheckBox)x.Checked = false; // also didn't work
            }
        }

I am sure this is something simple, but I can not find how to solve the problem. I was able to write the same procedure in vb.net, but I do not want to use this

+3
source share
5 answers

Try

((CheckBox)x).Checked = false;

As you wrote it, the compiler understands

(CheckBox)(x.Checked) = false;
+2
source

You need to put parentheses around the entire casting operation:

((CheckBox)x).Checked = false;
+7
source

You can definitely clean up your code a bit (and also fix the problem with parentheses):

foreach(var x in panel1.Controls)
{
    var checkbox = x as Checkbox;
    if(checkbox != null) checkbox.Checked = false;
}
+6
source
foreach(Checkbox box in panel1.Controls.OfType<CheckBox>())
{
  box.Checked = true;
}
+3
source

x is still an object, so you need to drop the object on the checkbox

((Checkbox)x).Checked = false;
0
source

All Articles