简体   繁体   English

如何遍历表单上的所有复选框?

[英]How can I iterate through all checkboxes on a form?

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? 在运行时,我如何迭代它们中的每一个,以便获得它们的值和ID?

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: 使用IEnumerable可以选择如何存储结果,还可以使用linq:

var checkedBoxes = control.AllControls<CheckBox>().Where(c => c.Checked);

If it is Windows Forms , you can try something like this: 如果是Windows Forms ,您可以尝试这样的事情:

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. 请记住,容器控件可以包含子项,因此您可能也想检查它们。

Like this, maybe (if it's in Windows Forms ): 像这样,也许(如果它在Windows窗体中 ):

foreach(var checkBox in myForm.Controls.OfType<CheckBox>())
{   
   //Do something.
}

创建它们后,获取值的引用列表,然后您可以遍历列表。

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> ,所有复选框状态都在列表中,即使它们在列表中的UI更改也会更改。

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 :) 希望这可以帮助 :)

myForm.Controls.OfType<CheckBox>().ToList().ForEach(c => c...);

如果复选框在GroupBox或Panel中,请使用其名称而不是'myForm'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM