You can recursively traverse the hierarchy of the controls on a Page and just get the controls that are CheckBoxes
In your page you can declare a member that will be used to store the checkboxes:
private List<CheckBox> checkBoxes = new List<CheckBox>();
Using a recursive method you can traverse the controls structure:
public void TraverseHierarchy(ControlCollection controls)
{
foreach (Control c in controls)
{
CheckBox checkBox = c as CheckBox;
if (checkBox != null)
{
checkBoxes.Add(checkBox);
}
if (c.Controls.Count > 0)
{
TraverseHierarchy(c.Controls);
}
}
}
And you can call this by providing the controls collection of the Page:
TraverseHierarchy(Page.Controls);
However a problem with the above code is that there are certain controls that inherit from the CheckBox control. Like the RadioButton
for instance. So that control will also be matched present in your collection because the as
is valid.
What you could do is either do further filtering based on a certain property of your checkboxes. For instance if your ID
naming is consistent across your checkboxes you can also check that the ID property starts with a specific prefix:
public void TraverseHierarchy(ControlCollection controls)
{
foreach (Control c in controls)
{
CheckBox checkBox = c as CheckBox;
if (checkBox != null)
{
if (checkBox.ID.StartsWith("cb"))
{
checkBoxes.Add(checkBox);
}
}
if (c.Controls.Count > 0)
{
TraverseHierarchy(c.Controls);
}
}
}
Or you could eliminate the controls that extend the CheckBox by using the is
operator but that will be an extra hit on performance and quite an ugly solution.