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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With