Reputation: 15
I have a little problem about checkboxes. I want to hide the boxes that are selected when I press the button.
I wrote a piece of code like
foreach (CheckBox button in Controls)
{
if (button.Checked == true)
{
button.Hide();
}
}
It works but I get a logical error. How can I solve this problem?
Upvotes: 0
Views: 1722
Reputation: 216358
The problem is the use of the Controls collection. This collection contains all the controls hosted by the form container. Trying to assign a control from this collection directly to a CheckBox results in a casting error.
Because not all controls in the form are checkboxes, you need to apply your logic only to checkbox controls.
It is easy with OfType IEnumerable extension
foreach (CheckBox button in this.Controls.OfType<CheckBox>())
{
if (button.Checked)
button.Hide();
}
This has also the advantage to allow the direct assignement to a variable of type CheckBox.
Upvotes: 2