按名称控制,包括儿童

时间:2012-01-05 03:05:23

标签: c# .net winforms controls

我正试图通过名字获得控制权。我写了以下代码:

public Control GetControlByName(string name)
{
    Control currentControl; 

    for(int i = 0,count = Controls.Count; i < count; i++)
    {
        currentControl = Controls[i];

        if (currentControl.HasChildren)
        {
            while (currentControl.HasChildren)
            {
                for(int x = 0,size = currentControl.Controls.Count; x < size; x++)
                {
                    currentControl = currentControl.Controls[x];

                    if (currentControl.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
                    {
                        return currentControl;
                    }
                }
            }
        }
        else
        {
            if (currentControl.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
            {
                return currentControl;
            }
        }
    }

    return null;
}

它只返回null。有人可以指出我的错误吗?欢迎任何帮助或改进此代码的方法。

2 个答案:

答案 0 :(得分:12)

只需使用Controls集合Find方法:

            var aoControls = this.Controls.Find("MyControlName", true);
            if ((aoControls != null) && (aoControls.Length != 0))
            {
                Control foundControl = aoControls[0];
            }

答案 1 :(得分:1)

我实际上在工作中写了一些扩展方法来做这件事:

public static class MyExensions ()
{
    public static Control FindControlRecursively (this Control control, string name)
    {
        Control result = null;

        if (control.ID.Equals (name))
        {
            result = control;
        }
        else
        {
            foreach (var child in control.Children)
            {
                result = child.FindControlRecursively (name);

                if (result != null)
                {
                    break;
                }
            }
        }

        return result;
    }

    public static T FindControlRecursively<T> (this Control control, string name)
        where T: Control
    {
        return control.FindControlRecursively (name) as T;
    }
}

注意:为简单起见删除了空检查。

您可以使用它来查找表单上的TextBox,如下所示:

public class MyForm : Form
{
    public void SetSomeText ()
    {
        var control = this.FindControlRecursively<TextBox> ("myTextboxName");

        if (control != null)
        {
            control.Text = "I found it!";
        }

        // Or...

        var control2 = this.FindControlRecursively ("myTextboxName2") as TextBox;

        if (control != null)
        {
            control2.Text = "I found this one, also!";
        }
    }
}

修改

当然,这是一个深度优先算法,根据您的控制链的深度,这可能会很慢。如果您发现它太慢,您可以重写它以使用广度优先算法。