Using a foreach loop to retrieve TextBox's within a GroupBox

前端 未结 4 1072
孤城傲影
孤城傲影 2020-12-17 06:06

I have ten group boxes in a WinForm. Each group box contains 10 text boxes, and I have defined each TextBox name. How can I get each text box usin

相关标签:
4条回答
  • 2020-12-17 06:41
    foreach (var ctrl in gbDatabaseColumns.Controls)
    {
         if (ctrl is DevExpress.XtraEditors.TextEdit)
         {
            StoreTextEdit(config, (ctrl as DevExpress.XtraEditors.TextEdit));
         }
    }
    
    0 讨论(0)
  • 2020-12-17 06:43

    Here is my suggestion:

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

    Or having it in one loop:

    foreach (var textBox in Controls.OfType<GroupBox>().SelectMany(groupBox => groupBox.Controls.OfType<TextBox>()))
    {
        // Do Something
    }
    
    0 讨论(0)
  • 2020-12-17 06:50

    try following code,

    Control.ControlCollection coll = this.Controls;
    foreach(Control c in coll) {
      if(c != null)
    }
    
    0 讨论(0)
  • 2020-12-17 06:51
     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.
                 }
              }
           }
     }
    

    But if you have defined each TextBox name What's the point to get each TextBox by a loop?

    You could define a List<TextBox> to hold reference of each TextBox while creating them, then just go though the List to get access of each TextBox.

    0 讨论(0)
提交回复
热议问题