How can I iterate through all checkboxes on a form?
foreach(Control c in this.Controls)
{
if(c is CheckBox)
{
// Do stuff here ;]
}
}
I use a simple extension method that will work for any control type:
public static IEnumerable<T> AllControls<T>(this Control startingPoint) where T : Control
{
bool hit = startingPoint is T;
if (hit)
{
yield return startingPoint as T;
}
foreach (var child in startingPoint.Controls.Cast<Control>())
{
foreach (var item in AllControls<T>(child))
{
yield return item;
}
}
}
Then, you can use it like so:
var checkboxes = control.AllControls<CheckBox>();
Using IEnumerable lets you choose how to store the results, and also lets you use linq:
var checkedBoxes = control.AllControls<CheckBox>().Where(c => c.Checked);