Quick and dirty “dirty checking” for Windows form, C#
While designing a CRF, little short-cuts can save you lots and lots of time. This time-saver is straight-forward code-wise and should fit right into your C# code without much modification.
During CRF design time, I often have CRFs that have dozens and dozens of input controls (radio buttons, dropdowns, listboxes, textboxes…). I’d like to add OnChange handlers to all of these input controls so that I know when a change has been made. Basically, what it comes down to is I want to know when the form is dirty, but I don’t want to add all the handlers by hand. Fortunately, I didn’t have to and neither do you!
The code below is a recursive function which traverses the Control tree. Whenever it locates a control that can be classified as an input control, it attaches an event handler.
void AddOnChangeHandlerToInputControls(Control ctrl)
{
foreach (Control subctrl in ctrl.Controls)
{
if (subctrl is TextBox)
((TextBox)subctrl).TextChanged +=
new EventHandler(InputControls_OnChange);
else if(subctrl is CheckBox)
((CheckBox)subctrl).CheckedChanged +=
new EventHandler(InputControls_OnChange);
else if(subctrl is RadioButton)
((RadioButton)subctrl).CheckedChanged +=
new EventHandler(InputControls_OnChange);
else if(subctrl is ListBox)
((ListBox)subctrl).SelectedIndexChanged +=
new EventHandler(InputControls_OnChange);
else if(subctrl is ComboBox)
((ComboBox)subctrl).SelectedIndexChanged +=
new EventHandler(InputControls_OnChange);
else
{
if (subctrl.Controls.Count > 0)
this.AddOnChangeHandlerToInputControls(subctrl);
}
}
}
Keep in mind the recursion is necessary, because the Controls property field only lists a control’s immediate children. Those immediate children may have children of their own. That’s right… exactly like a family tree! The use of recursion creates an elegant way to traverse the control’s control tree.
I’ve only picked up on the simplest input controls. It should be straight-forward to extend this for other controls like a DateTimePicker or a CheckedListBox (although the CheckedListBox is a little tricky because it uses a different type of event handler).
void InputControls_OnChange(object sender, ItemCheckEventArgs e)
{
// Do something to indicate the form is dirty like:
// this.formIsDirty = true;
}
All the event handler does is set a flag which indicates the form is dirty. How you process the dirty flag is up to you, and there you have it! Hopefully, you’ve saved a few hours of manually adding event handlers!
To receive updates on new articles, subscribe to CRF Design today!











