Search code examples
c#testingloopsforeachsplitcontainer

How to check all textboxes inside a splitcontainer?


My program uses a split container which both panels 1 & 2 have text boxes. I am trying to run a check when the program is attempting to close that prompts users to save. I tried the following code but it doesn't seem to work since the text boxes are within a splitcontaier (just guessing).

private void button1_Click(object sender, EventArgs e)
    {
        foreach ( TextBox tb in this.Controls.OfType<TextBox>()) 
        {
            tb.Text = "Save";

        }
    }

When I use the bit of code on a program that has text boxes within the form itself, it works. When I try to use it where the textboxes are within panels it does not. It also doesn't work if I use code specifying the splitcontainer

  foreach ( TextBox tb in splitContainer1.Controls.OfType<TextBox>()) 
       {               
           tb.Text = "Save";
        }

How can I get it to address the textboxes within the splitcontainer?

I can specify the text boxes within a specific panel and do them each 1 at a time:

//this works, but only populates those text boxes in panel1
foreach ( TextBox tb in splitContainer1.Panel1.Controls.OfType<TextBox>() ) 
       {               
           tb.Text = "save";
        }

But I still can't seem to do this in 1 test. I'm having to check both panel independently.


Solution

  • You need something like Leepie commented about, recursively check for all controls of a certain type.

    With a method like this you can do an action method on every TextBox.

    public void ModifyControl<T>(Control root, Action<T> action) where T : Control
    {
        if (root is T)
            action((T)root);
        // Call ModifyControl on all child controls
        foreach (Control control in root.Controls)
            ModifyControl<T>(control, action);
    }
    

    You call it like:

    ModifyControl<TextBox>(splitContainer1, tb => tb.Text = "Save");