使用foreach循环检索GroupBox中的TextBox

我在WinForm有十个组框。 每个组框包含10个文本框,我已定义每个TextBox名称。 如何使用foreach循环获取每个文本框?

  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引用,然后只需通过List来访问每个TextBox

这是我的建议:

 foreach(var groupBox in Controls.OfType()) { foreach(var textBox in groupBox.Controls.OfType()) { // Do Something } } 

或者将它放在一个循环中:

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

尝试以下代码,

 Control.ControlCollection coll = this.Controls; foreach(Control c in coll) { if(c != null) } 
 foreach (var ctrl in gbDatabaseColumns.Controls) { if (ctrl is DevExpress.XtraEditors.TextEdit) { StoreTextEdit(config, (ctrl as DevExpress.XtraEditors.TextEdit)); } }