views:

327

answers:

2

I'm sure this is an easy problem, but i can't think of a way (other than using javascript to force a postback) to get a list of checkboxes in the asp.net code behind.

each checkbox is in a seperate custom control so i can't use a checkboxlist.

any help would be much appreciated.

Thanks in advance

+1  A: 

If you have a usercontrol with N number of checkboxes, you need to expose a public property holding the collection of ids, controls...whatever it is that you need access to from the parent container.

rick schott
+1 - agreed, modify the custom control's interface to either expose the checkbox's id, the checkbox itself, or the state that Checkbox.Checked represents.
Jeff Sternal
You could simply do a foreach on the controls collection of the UserControl, iterating through and checking for checkboxes using the is.
Nissan Fan
A: 

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.

Mircea Grelus