In my code I need to loop through the controls in a GroupBox and process the control only if it 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 looping through all the controls and processing only the combo boxes is is possible to get only the combo boxes from the GroupBox? Something like this:
foreach (System.Windows.Forms.Control grpbxChild in this.gpbx.Controls.GetControlsOfType(ComboBox))
{
// Process here
}
Since you are using C# 2.0, you're pretty much out of luck. You could write a function yourself. In C# 3.0 you'd just 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'd use like:
foreach (ComboBox c in GetControlsOfType<ComboBox>(groupBox.Controls))
{
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With