Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through controls

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
}
like image 253
SO User Avatar asked Dec 31 '22 00:12

SO User


1 Answers

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))
{
    // ...
}
like image 67
mmx Avatar answered Jan 13 '23 20:01

mmx