Looping Through Controls

In my code, I need to scroll the controls in the GroupBox and process the control only if it is a ComboBox. I am using the code:

foreach (System.Windows.Forms.Control grpbxChild in this.gpbx.Controls) { if (grpbxChild.GetType().Name.Trim() == "ComboBox") { // Process here } } 

My question is: instead of iterating over all controls and processing only combined fields, can you only get combined fields from GroupBox? Something like that:

 foreach (System.Windows.Forms.Control grpbxChild in this.gpbx.Controls.GetControlsOfType(ComboBox)) { // Process here } 
+4
source share
5 answers

Since you are using C # 2.0, you are pretty much out of luck. You can write the function yourself. In C # 3.0, you simply do:

 foreach (var control in groupBox.Controls.OfType<ComboBox>()) { // ... } 

C # 2.0 solution:

 public static IEnumerable<T> GetControlsOfType<T>(ControlCollection controls) where T : Control { foreach(Control c in controls) if (c is T) yield return (T)c; } 

which you would use for example:

 foreach (ComboBox c in GetControlsOfType<ComboBox>(groupBox.Controls)) { // ... } 
+8
source

Mehrdad is absolutely right, but your syntax (even if you use C # 2.0) is too complicated.

I find this easier:

 foreach (Control c in gpBx.Controls) { if (c is ComboBox) { // Do something. } } 
+2
source
 if (!(grpbxChild is System.Windows.Forms.Combobox)) continue; // do your processing goes here grpbxChild.Text += " is GroupBox child"; 
0
source
 foreach (System.Windows.Forms.Control grpbxChild in this.gpbx.Controls) { if (grpbxChild is ComboBox) { // Process here } } 
0
source
 foreach (Control items in this.Controls.OfType<GroupBox>()) { foreach (ComboBox item in items.Controls.OfType<ComboBox>()) { // your processing goes here } } 
0
source

All Articles