views:

928

answers:

5

I have a form that has many dynamically generated checkboxes. At runtime, How can I iterate through each of them so I can get their value an IDs?

Thanks, John

+7  A: 
foreach(Control c in this.Controls)
{
   if(c is CheckBox)
   {
   // Do stuff here ;]
   }
}
Michal Franc
+1  A: 

when they are created have a list of references to the values, then you can iterate over the list

harryovers
+2  A: 

Like this, maybe (if it's in WinForms):

foreach(var checkBox in myForm.Controls.OfType<CheckBox>())
{   
   //do smth 
}
Yacoder
+5  A: 

If it is win forms you can try something like this

private void button1_Click(object sender, EventArgs e)
        {
            Dictionary<string, bool> checkBoxes = new Dictionary<string, bool>();
            LoopControls(checkBoxes, this.Controls);
        }

        private void LoopControls(Dictionary<string, bool> checkBoxes, Control.ControlCollection controls)
        {
            foreach (Control control in controls)
            {
                if (control is CheckBox)
                    checkBoxes.Add(control.Name, ((CheckBox) control).Checked);
                if (control.Controls.Count > 0)
                    LoopControls(checkBoxes, control.Controls);
            }
        }

Remember that contrainer controls can contain children, so you might want to check those too.

astander
+5  A: 

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);
Robert Jeppesen
+1 they can be nested, good point, and using lambdas is always a plus )
Yacoder
This is probably more useful than Control.Controls
ohadsc