简体   繁体   中英

Programming Skill Tester (Problem) v2.0

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'.

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
    }
}

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

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;  
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM