开发者

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 late开发者_如何学Pythonr I want more textboxes in my winforms?


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))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜