Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have event fire whenever any changes made to textboxes, comboboxs, etc. inside form

I'm working with a C# WinForm. It has more than a dozen text boxes, combo boxes, and check boxes. The winform displays information that is retrieved from a database. There is a save button on the form that is disabled. I want to be able to enable it when any of the text boxes/combo boxes/ check boxes are changed.

Is there an easy to way to do this without adding separate event handlers to each of these items?

like image 528
Shaun Avatar asked Jul 12 '12 16:07

Shaun


1 Answers

Here is enough to get you stared. You may need to add extra foreach loops for other control types as needed. The nice thing is that you only need a few lines of code per Control type, not per instance, with this approach.

private void addHandlers()
{
    foreach (TextBox control in Controls.OfType<TextBox>())
    {
        control.TextChanged += new EventHandler(OnContentChanged);
    }
    foreach (ComboBox control in Controls.OfType<ComboBox>())
    {
        control.SelectedIndexChanged += new EventHandler(OnContentChanged);
    }
    foreach (CheckBox control in Controls.OfType<CheckBox>())
    {
        control.CheckedChanged += new EventHandler(OnContentChanged);
    }
}

protected void OnContentChanged(object sender, EventArgs e)
{
    if (ContentChanged != null)
        ContentChanged(this, new EventArgs());
}

public event EventHandler ContentChanged;

After modifying the addHandlers method to support all of your controls, and calling it after adding all of the controls to your form, you can simply subscribe to the ContentChanged event for doing whatever might need to happen anytime something on the form changed (i.e. enable/disable a save button).

like image 87
Servy Avatar answered Oct 05 '22 23:10

Servy