How can I iterate through all checkboxes on a form?

后端 未结 6 851
[愿得一人]
[愿得一人] 2020-11-29 08:36

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 and IDs?

相关标签:
6条回答
  • 2020-11-29 08:51

    When they are created, get a list of references to the values, and then you can iterate over the list.

    0 讨论(0)
  • 2020-11-29 08:51

    I know that this is old, but It was easy as I can imagine.

    Just add all checkboxes into a List<Checkbox>, all checkboxes state are in the list and even if they change in the UI in the list changes too.

    List<Checkbox> checkboxes = new List<Checkboxes>();
    checkboxes.Add(chk1);
    checkboxes.Add(chk2);
    //So add all checkboxes you wanna iterate
    
    foreach(Checkbox checkbox in checkboxes){
        //Do something using checkbox object
    }
    

    Hope this helps :)

    0 讨论(0)
  • 2020-11-29 08:53
    foreach(Control c in this.Controls)
    {
       if(c is CheckBox)
       {
       // Do stuff here ;]
       }
    }
    
    0 讨论(0)
  • 2020-11-29 08:57

    If it is Windows 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 container controls can contain children, so you might want to check those too.

    0 讨论(0)
  • 2020-11-29 09:07

    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);
    
    0 讨论(0)
  • 2020-11-29 09:12

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

    foreach(var checkBox in myForm.Controls.OfType<CheckBox>())
    {   
       //Do something.
    }
    
    0 讨论(0)
提交回复
热议问题