简体   繁体   English

对动态添加的嵌套控件进行迭代

[英]Iteration over dynamically added nested controls

I have a GroupBox on an WinForm. 我在WinForm上有一个GroupBox。 Another GroupBox is added in run time within the first GroupBox. 在运行时在第一个GroupBox中添加了另一个GroupBox。

Few PictureBox controls are added within the second GroupBox. 在第二个GroupBox中添加了很少的PictureBox控件。

Now I would like to iterate the PictureBoxes. 现在,我想迭代PictureBoxes。

Currently my code is: 目前,我的代码是:

foreach (Control gbFirst in this.Controls)
{
    GroupBox firstGroupBox = gbFirst as GroupBox; //First GroupBox
    if (firstGroupBox != null)
    {
        foreach (Control gbSecond in firstGroupBox.Controls)
        {
            GroupBox secondGroupBox = gbSecond as GroupBox; //Second groupBox
            if (secondGroupBox != null)
            {
                foreach (Control item in secondGroupBox.Controls)
                {
                    var pb = item as PictureBox; // PictureBox
                    if (pb != null)
                    {
                        string pbTag = pb.Tag.ToString();
                        string customTag = ipAddress + "OnOff";
                        if (pb.Tag.ToString() == ipAddress + "OnOff")
                        {
                            MethodInvoker action = delegate
                            {
                                pb.Image = Properties.Resources.MobiCheckerOnPng16;
                            };
                            pb.BeginInvoke(action);
                            break;
                        }
                    }
                }
            }

        }
    }
}

But, unlike the above, I think there may be an easy or smart way to do it. 但是,与上述不同,我认为可能有一种简单或聪明的方法来做到这一点。

Is it so? 是这样吗?

A generic function to use for any control type in any container at any levels: 在任何级别的任何容器中用于任何控件类型的通用函数:

public static List<T> FindControls<T>(Control container, bool dig) where T : Control
{
    List<T> retVal = new List<T>();
    foreach (Control item in container.Controls)
    {
        if (item is T)
            retVal.Add((T)item);
        if (dig && item.Controls.Count > 0)
            retVal.AddRange(FindControls<T>(item, dig));
    }
    return retVal;
}

The dig variable controls whether or not to iterate through child container controls. dig变量控制是否迭代子容器控件。 For example if you want to find all PictureBox controls starting from your first GroupBox (gbFirst), you must call 例如,如果要查找从第一个GroupBox(gbFirst)开始的所有PictureBox控件,则必须调用

FindControls<PictureBox>(gbFirst, true);

If set dig to false, only controls in the input cotainer will be enumerated. 如果将dig设置为false,则仅枚举输入容器中的控件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM