Checking Controls in multiple panels

本小妞迷上赌 提交于 2019-12-12 18:07:41

问题


I have a programs with multiple panels with textboxes that will share a value. for example a street address. I have coded a way for these values to be updated by sharing a TextChanged event, however the event does not search the panels for the controls, it will only affect a TextBox in the main form window.

Code.

private void matchtextbox(object sender, EventArgs e)
{
    TextBox objTextBox = (TextBox)sender;
    string textchange = objTextBox.Text;           

    foreach (Control x in this.Controls)
    {
        if (x is TextBox)
        {
            if (((TextBox)x).Name.Contains("textBoxAddress"))
            {
                ((TextBox)x).Text = textchange;
            }
        }
    }
}

So say panel1 contains textBoxAddress1, panel contains textBoxAddress2, both with this TextChanged event. they do not update each other when typing. However if they are outside the panel they do.

Final Code which is the resolution based on a lovely community member below.

private void Recursive(Control.ControlCollection ctrls)
{
    foreach (var item in ctrls)
    {
        if (item is Panel)
        {
            Recursive(((Panel)item).Controls);
        }
        else if (item is TextBox)
        {
            if (((TextBox)item).Name.Contains("txtSAI"))
            {
                ((TextBox)item).Text = textchange;
            }
        }
    }
}

private void matchtextbox(object sender, EventArgs e)
{
    TextBox objTextBox = (TextBox)sender;
    textchange = objTextBox.Text;  
    Recursive(Controls);
}

string textchange;

回答1:


You need a recursive method for this purpose:

private void Recursive(IEnumerable ctrls)
{
    foreach (var item in ctrls)
    {
        if (item is Panel)
        {
            Recursive(((Panel)item).Controls);
        }
        else if(item is TextBox)
        {
            if (((TextBox)item).Name.Contains("textBoxAddress"))
            {
                ((TextBox)item).Text = textchange;
            }
        }
    }
}

Then call it like this:

private void matchtextbox(object sender, EventArgs e)
{
     Recursive(Controls);
}


来源:https://stackoverflow.com/questions/34675921/checking-controls-in-multiple-panels

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!