tags:

views:

309

answers:

3

If you haven't read the first problem do so know to catch up to speed. Now then, how do I go about clearing these check boxes? I tried using the same approach that @colithium told me to use for checking the state of all the check boxes, but when I ran the program and clicked clear I got the following runtime error:

Unable to cast object of type 'System.Windows.Forms.Button' to type 'System.Windows.Forms.CheckBox'.

A: 

Set CheckBox.Checked to false. If that's not what you need, please provide more information in the question.

Jon Skeet
+6  A: 

I am guessing you are running a foreach over all your controls and forgot to look if the control is actually a checkbox.

foreach (Control c in this.Controls) {
    CheckBox cb = c as CheckBox;
    if (cb!=null) {
        //do your logic
    }
}
Stormenet
+1  A: 

I assume your method looks something like this:

private void clearButton_Click(object sender, EventArgs e)  
{  
    CheckBox cb = (CheckBox)sender;  
    cb.Checked = false;  
}

In this case, the "Sender" is the clear button, not a check box. Borrowing from Stormenet's answer:

private void clearButton_click(object sender, EventArgs e)  
{    
    foreach (Control c in this.Controls)   
    {  
        CheckBox cb = c as CheckBox;  
        if (cb != null)  
        {  
            cb.Checked = false;  
        }
    }
}

NascarEd