加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 通过控件循环

发布时间:2020-12-16 07:26:04 所属栏目:asp.Net 来源:网络整理
导读:在我的代码中,我需要遍历GroupBox中的控件并仅在它是ComboBox时处理控件.我正在使用代码: foreach (System.Windows.Forms.Control grpbxChild in this.gpbx.Controls){ if (grpbxChild.GetType().Name.Trim() == "ComboBox") { // Process here }} 我的问题
在我的代码中,我需要遍历GroupBox中的控件并仅在它是ComboBox时处理控件.我正在使用代码:

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

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

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

解决方法

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

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

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;
}

您使用的方式如下:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读