简体   繁体   English

C#中不同面板中具有相同名称的控件

[英]controls with same name in different panels in C#

In my form, I created two panels panel1 and panel2 , within each panel I created one button named button1 and button2 respectively. 在我的表单中,我创建了两个面板panel1panel2 ,在每个面板中我创建了一个分别名为button1button2的按钮。 if I want to add event handler using, 如果我想使用添加事件处理程序,

this.button1.Click += buttonEvent;

is fine. 很好 But, when I use foreach for each controls in form, It is not detected. 但是,当我对窗体中的每个控件使用foreach时,未检测到它。 Whats the problem here? 这里有什么问题?

public myForm1() 
{
    InitializeComponent();
    foreach (Control c in this.Controls) 
    {
        TextBox tb = c as TextBox;
        if (tb != null)
        {  
            tb.TextChanged += textChanged;
        }
    }
}

How can I access the control in each of my panel using foreach ? 如何使用foreach访问每个面板中的控件?

You have to iterate over the controls in panel1 and panel2 instead of myForm1 . 您必须遍历panel1panel2的控件,而不是myForm1

public myForm1() 
{
    InitializeComponent();
    foreach(Control c in panel1.Controls)
    {
        TextBox tb = c as TextBox;
        if(tb != null)
        {
            tb.TextChanged += textChanged;
        } 
    }
}

EDIT 编辑

To get the panels from the form: 要从表单获取面板:

for(int i = 0; i < 2; i++)
{
    Panel p = this.Controls["panel" + i];
    foreach(Control c in p.Controls)
    {
        TextBox tb = c as TextBox;
        if(tb != null)
        {
            tb.TextChanged += textChanged;
        }
    }
}

In your Form the Controls Collection only got the panels. 在您的窗体中,控件集合仅包含面板。 Because a panel is a Container (as the Form) it has its own Controls Collection. 因为面板是容器(作为窗体),所以它具有自己的控件集合。 So you have to iterate recursively for getting all subcontrols. 因此,您必须递归迭代以获取所有子控件。 So that if a new IContainerControl is detected like panel or usercontrol etc., you check them too. 这样,如果检测到新的IContainerControl(如面板或用户控件等),也可以对其进行检查。

In your case the panels Controls Collection will contain the button. 在您的情况下,面板“控件集合”将包含该按钮。

For example this method should search for an item: 例如,此方法应搜索一个项目:

The container should be your form. 容器应该是您的表格。

private Control SearchControl(IContainerControl container, string name)
{
    foreach (Control control in this.Controls)
    {
        if (control.Name.Equals(name))
        {
            return control;
        }

        if (control is IContainerControl)
        {
            return SearchControl(control as IContainerControl, name);
        }
    }

    return null;
}

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

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