tags:

views:

96

answers:

2

I have a form with several groupboxes, each containing controls several checkboxes. I want to clear the checkboxes.

I use the following code. However it does not get cleared.

What am i doing wrong?

foreach (Control ctrl in this.Controls)
{
     if (ctrl is CheckBox)
         ((CheckBox)(ctrl)).Checked = false;                    
}

Once again the checkboxes are within groupboxes.

+1  A: 

When the checkboxes are within another control, in your case groupboxes, you need to use recursion to set the property checked of the checkboxes. The collection this.Controls only returns the closest child controls.

setCheckBoxesUnChecked(this);

public function setCheckBoxesUnChecked(Control parent)
{
    foreach (Control ctrl in parent.Controls)
    {
        if (ctrl is CheckBox)
            ((CheckBox)ctrl).Checked = false;

        setCheckBoxesUnChecked(ctrl);
    }
}
Joop
setCheckBoxesUnChecked does not appear in intellisense, and i want to uncheck the checked checkboxes not vice-versa
tecno
oops sorry about that; working on it....
tecno
thanks Joop, it works perfectly!
tecno
You're more than welcome.
Joop
A: 

private void btnClear_Click(object sender, EventArgs e) { setCheckBoxesUnChecked(this); }

    private void setCheckBoxesUnChecked(Control parent)
    {
        foreach (Control ctrl in parent.Controls)
        {
            if (ctrl is GroupBox)
                setCheckBoxesUnChecked(ctrl);
            if (ctrl is CheckBox)
                ((CheckBox)ctrl).Checked = false;
        }
    }
tecno