-2

I am trying to uncheck all the checkboxes in all the panels I have. This is different from other questions because it is for every panel that has a checkbox. The code I have right now unchecks all the checkboxes in the form but not in all the panels.

foreach (CheckBox control in this.Controls.OfType<CheckBox>())
{
    control.Checked = false;
}

I have a bunch of panels and checkboxes in them and there has to be a simple way to uncheck them all.

this does it to every checkbox in my form instead of only panels my code:

private void button16_Click(object sender, EventArgs e)
{
    clearStuff((Control.ControlCollection)this.Controls);
}
private void clearStuff(Control.ControlCollection obj)
{
    foreach (Control control in obj)
    {
        if (control.HasChildren)
            clearStuff(control.Controls);
        else
            if (control is CheckBox)
            {
                CheckBox check_box = (CheckBox)control;
                check_box.Checked = false;
           }
    }
}

this works but it could be refactored

foreach (Panel control2 in this.Controls.OfType<Panel>())
{
    foreach (CheckBox control1 in control2.Controls.OfType<CheckBox>())
    {
        control1.Checked = false;
    }
}
Mr Mods
  • 33
  • 1
  • 7
  • Assuming you're not maintaining a list of controls in your code, you need to search the children of controls as well (and their descendents). Your code only checks one layer. Here's a post that shows different ways of doing it http://stackoverflow.com/questions/3419159/how-to-get-all-child-controls-of-a-windows-forms-form-of-a-specific-type-button – keyboardP Jul 19 '16 at 23:31
  • You must use recursive methods. If control has a child, then go inside and check if checkBox. –  Jul 19 '16 at 23:36
  • Am I able to uncheck them all with the codes in that link? – Mr Mods Jul 19 '16 at 23:36
  • Or any of the other many related questions: https://stackoverflow.com/search?page=3&tab=newest&q=%5bc%23%5d%20%5bwinforms%5d%20all%20controls%20recursive – Peter Duniho Jul 19 '16 at 23:40
  • @MrMods - The code returns all controls of a specific type so no reason why you can't iterate through and set the flag to false. – keyboardP Jul 19 '16 at 23:42
  • foreach within a foreach, or a seperate foreach for just panels and their children...sky is the limit on this one. – Gary.Taylor717 Jul 19 '16 at 23:51

1 Answers1

0
private void button16_Click(object sender, EventArgs e)
{
    clearStuff((Control.ControlCollection)this.Controls);
}

public void clearStuff(Control.ControlCollection controls)
{
    foreach (Control c in controls)
    {
        if (c is Panel)
        {
            clearStuff(c);
        }
        else if (c is Checkbox)
        {
            c.Checked = false;
        }
    }
}
kimbaudi
  • 13,655
  • 9
  • 62
  • 74