You might think about whether your best strategy is to do something
immediately whenever a CheckBox's 'CheckState Property is changed compared to taking
deferred action based on reading the current state of a group of CheckBoxes. You often find the "deferred action" strategy used in configuration user-interfaces in combination with an "Apply" button.
A slight variation using 'OfType<> and Linq:
public int HowManyChecked(Control container)
{
return container.Controls.OfType<CheckBox>().Where(cbx => cbx.Checked).Count();
}
Note: this will not throw an error if there are no CheckBoxes. 'OfType<> requires NET FrameWork 4.5, or later.
However, it seems logical to me that you would want to
do something based on which CheckBoxes are checked; so:
public IEnumerable<CheckBox> GetCbxChecked(Control container)
{
return container.Controls.OfType<CheckBox>().Where(cbx => cbx.Checked);
}
A use-case example:
private void button1_Click(object sender, EventArgs e)
{
var chkd = GetCbxChecked(panel1);
if(chkd.Count() > 0)
{
foreach (var cbx in chkd)
{
switch (cbx.Name)
{
case "checkBox1":
break;
case "checkBox2":
break;
case "checkBox3":
break;
}
}
}
}