0

Ok so here is my problem:I have a form with 10 user control (they are all the same) and they each include 1 textbox, 1 combobox and 5 checkbox.

By default everything is disabled, but with another checkbox the user will enabled either the textbox or the combobox or all 5 checkboxes.

I could easly do it by doing something like

    ucPlayer1.name.Enabled = true;
    ucPlayer2.name.Enabled = true;

etc .. but it seems unnecessary

Before I wasn't using any usercontrol so I could do something like:

    foreach (Control c in this.Controls)
    {
        if (c is TextBox && c != null)
           ((TextBox)c).Enabled = true;
    }

but now, i'm stuck, I can't get a working loop, i tried something like:

    foreach(UserControl uc in Controls)

But it doesn't work.

Any ideas ??

1 Answer 1

1

Try something like this. If it is usercontrol then call the same method recursively.

private void DoItRecursive(Control parent)
{
    foreach (Control c in parent.Controls)
    {
        if(c is UserControl)
            DoItRecursive(c);
        else if (c is TextBox)
            c.Enabled = true;
    }
}

Then use it like this

DoItRecursive(this);

Where this refers to Form typically.

Note: I've removed c != null checking from your code because is keyword takes care of that. You don't need to, and casting c to TextBox is redundant.

Sign up to request clarification or add additional context in comments.

2 Comments

It works perfectly!! I didn't even have to change anything!! thanks a lot :D
Also note this will work only when you have UserControl, If you use Panel or something like that this will fail. In that case you need to use if(c.Controls.Count > 0) DoItRecursive(c);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.