C#: Detecting Control Value Changes in Forms
By admin on Jul 14, 2010 in .NET
To easily detect control text or value changes in a Form, you can use reflection and attach the event handler to the TextChanged or ValueChanged event
1: /// <summary>
2: /// Sets the form state change handlers.
3: /// </summary>
4: /// <param name="parent">The parent.</param>
5: private void SetFormStateChangeHandlers(Control parent)
6: {
7: isFormChanged = false;
8:
9: foreach (Control control in parent.Controls)
10: {
11: // Attach to text changed event
12: EventInfo eventInfo = control.GetType().GetEvent("TextChanged",
13: BindingFlags.Instance | BindingFlags.Public);
14: if (eventInfo != null)
15: {
16: eventInfo.AddEventHandler(control, new EventHandler(ControlStateChanged));
17: }
18:
19: // Attach to value changed event
20: eventInfo = control.GetType().GetEvent("ValueChanged",
21: BindingFlags.Instance | BindingFlags.Public);
22: if (eventInfo != null)
23: {
24: eventInfo.AddEventHandler(control, new EventHandler(ControlStateChanged));
25: }
26:
27: // handle container controls which might have child controls
28: if (control.Controls.Count > 0)
29: {
30: SetFormStateChangeHandlers(control);
31: }
32: }
33: }
34:
35: /// <summary>
36: /// Controls the state changed.
37: /// </summary>
38: /// <param name="sender">The sender.</param>
39: /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
40: private void ControlStateChanged(object sender, EventArgs e)
41: {
42: isFormChanged = true;
43: }
Call SetFormStateChangeHandler when the Form loads, passing “this” as the initial parameter.
When the text or value is changed for any control, isFormChanged is set to true.
Sorry, comments for this entry are closed at this time.