Reputation: 113
I am trying to write a code which will uncheck all checkBoxes in my form when a button is clicked. I know that I could do
checkBox1.Checked = false;
checkBox2.Checked = false;
checkBox3.Checked = false;
and so on, but I have about 35 checkBoxes, so I was hoping to use a simpler code. I keep finding stuff online that looks like this;
foreach (Control cBox in this.Controls)
{
if (cBox is CheckBox)
{
((CheckBox)cBox).Checked = false;
}
}
And I was hoping to use something like that, instead of writing checkBox1.Checked = false;
about 70 times (because I have 2 buttons, both of which need to do various things and then uncheck all the boxes.
I saw another solution that involved a Stack Panel or some type of code that looked more like Javascript or HTML than C#, and also seemed to involved writing out each checkBox.Checked status as its own line, which doesn't save me any lines of code.
Any tips would be appreciated. Thanks all :)
Upvotes: 0
Views: 11555
Reputation: 7142
You can use C# 7.0+ pattern matching:
foreach(Control control in controls)
{
if (control is CheckBox chk) chk.Checked = false;
}
Upvotes: 1
Reputation: 113
Answering my own question with some info from my new pal @HandbagCrab:
foreach (Control cBox in tabPage1.Controls)
{
if (cBox is CheckBox)
{
((CheckBox)cBox).Checked = false;
}
}
Adding the tabPage1
fixed my issue. Before, I had been using this.Controls
which limited access to controls only within that dependency. I was still able to control other things based on the checkBoxes by naming them individually like checkBox1.Checked = false;
, but this was only because I called to them by name, rather than asking the code to look through all Controls
.
Upvotes: 3