Dusk
Dusk

Reputation: 2201

Set TextChanged event for textboxes in winforms

I've form with eight textboxes, and and now I want whenever any user performs textchanged event in any textbox, a button gets disabled.

Should I need to bind to textChanged event to all the textboxes, or is there any better approach?

What if later I want more textboxes in my winforms?

Upvotes: 2

Views: 2991

Answers (1)

Migwell
Migwell

Reputation: 20107

If for some reason you don't want to have to bind the same event handler to 8+ text boxes in the designer, you could do so programatically on the Form load event:

private void MainForm_Load(object sender, EventArgs e)
{
    foreach (Control maybeTextBox in Controls)
    {
         if (maybeTextBox is TextBox)
         { 
             maybeTextBox.TextChanged += new EventHandler(maybeTextBox_TextChanged);
         }
    }
}

The only problem with this is that if any of the TextBoxes are inside another control, you'll need to write a recursive find method like this:

public static Control[] GetControls(Control findIn)
{
    List<Control> allControls = new List<Control>();
    foreach (Control oneControl in findIn.Controls)
    {
        allControls.Add(OneControl);
        if (OneControl.Controls.Count > 0)
            allControls.AddRange(GetControls(oneControl));
    }
    return allControls.ToArray();
}

You can call that method on a form, so the original code will become:

foreach (Control maybeTextBox in GetControls(this))

Upvotes: 5

Related Questions