winforms 使用foreach循环检索GroupBox中的TextBox

zrfyljdw  于 2022-11-16  发布在  其他
关注(0)|答案(5)|浏览(326)

我在一个WinForm中有10个分组框。每个分组框包含10个文本框,并且我已经定义了每个TextBox的名称。如何使用foreach循环获取每个文本框?

axr492tv

axr492tv1#

foreach(Control gb in this.Controls)
 {
       if(gb is GroupBox)
       {
          foreach(Control tb in gb.Controls)
          {
             if(tb is TextBox)
             {
                 //here is where you access all the textboxs.
             }
          }
       }
 }

但是如果您已经定义了每个TextBox名称通过循环获取每个TextBox有什么意义呢?
您可以定义一个List<TextBox>来保存每个TextBox的引用,同时创建它们,然后只需通过List来访问每个TextBox

0yycz8jy

0yycz8jy2#

以下是我的建议:

foreach(var groupBox in Controls.OfType<GroupBox>())
{
    foreach(var textBox in groupBox.Controls.OfType<TextBox>())
    {
        // Do Something
    }
}

或者将其置于一个循环中:

foreach (var textBox in Controls.OfType<GroupBox>().SelectMany(groupBox => groupBox.Controls.OfType<TextBox>()))
{
    // Do Something
}
hmtdttj4

hmtdttj43#

请尝试以下代码,

Control.ControlCollection coll = this.Controls;
foreach(Control c in coll) {
  if(c != null)
}
lokaqttq

lokaqttq4#

foreach (var ctrl in gbDatabaseColumns.Controls)
{
     if (ctrl is DevExpress.XtraEditors.TextEdit)
     {
        StoreTextEdit(config, (ctrl as DevExpress.XtraEditors.TextEdit));
     }
}
cnwbcb6i

cnwbcb6i5#

foreach (Control txx in groupBox2.Controls)
{
    if (txx is TextBox)
        txx.Text = "";
    if (txx is ComboBox)
        txx.Text = "";
    // if (txx is DateTimePicker)
    //     txx.Text = ""; Datetimepicker text can't be erased
}

相关问题