2

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;
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109

1 Answers1

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);
}
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109