Reputation: 245
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?
Upvotes: 5
Views: 7862
Reputation: 148120
You have to go through through the controls and attach change event to every control. This article discuss the similar situation.
private void AssignHandlersForControlCollection(
Control.ControlCollection coll)
{
foreach (Control c in coll)
{
if (c is TextBox)
(c as TextBox).TextChanged
+= new EventHandler(SimpleDirtyTracker_TextChanged);
if (c is CheckBox)
(c as CheckBox).CheckedChanged
+= new EventHandler(SimpleDirtyTracker_CheckedChanged);
// ... apply for other desired input types similarly ...
// recurively apply to inner collections
if (c.HasChildren)
AssignHandlersForControlCollection(c.Controls);
}
}
Upvotes: 2
Reputation: 203824
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).
Upvotes: 5
Reputation: 3485
You can have all of the events hooked up to one handler, just have them all call the same function, there you have a bool flag mbSomethingChanged = true and enable the save button. Check the flag on form close, if you want to alert the user to save.
Upvotes: 0
Reputation: 4744
You can write a general purpose event handler that handles the event for all of them, but alas, no, there is no way to autogenerate event handlers in Visual Studio (nor should there be).
Upvotes: 0