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. 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. 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?


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.

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

You have to iterate over the controls in panel1 and panel2 instead of 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;
        }
    }
}
链接地址: http://www.djcxy.com/p/61572.html

上一篇: 自动调整包含tableLayoutPanel的面板

下一篇: 在C#的不同面板中使用相同名称的控件