循环控制

Ras*_*dit 4 asp.net controls c#-2.0

在我的代码中,我需要循环遍历GroupBox中的控件并仅在它是ComboBox时处理控件.我正在使用代码:

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

我的问题是:不是循环遍历所有控件而只处理组合框,而只能从GroupBox中获取组合框?像这样的东西:

foreach (System.Windows.Forms.Control grpbxChild in this.gpbx.Controls.GetControlsOfType(ComboBox))
{
    // Process here
}
Run Code Online (Sandbox Code Playgroud)

Meh*_*ari 8

由于您使用的是C#2.0,因此您运气不佳.你可以自己写一个函数.在C#3.0中你只需:

foreach (var control in groupBox.Controls.OfType<ComboBox>())
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

C#2.0解决方案:

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

您使用的方式如下:

foreach (ComboBox c in GetControlsOfType<ComboBox>(groupBox.Controls))
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)