How can a parent know if a child control chages

  • Thread starter Thread starter wzack
  • Start date Start date
W

wzack

We are building a framework in C#. One thing that we would like to do
is know when any child control (checkboxes, radio buttons, etc.) is
changed in a container of controls (such as a panel or a form). This
seems like it ought to be simple, but we cannot figure out how to do it
in .NET without writing code in each object.

Bill Zack
 
Bill,

You can use reflection to iterate over the events exposed by any
control, and then set up the appropriate event handlers (you can even set up
one generic event handler to handle ALL events in C# 2.0).

If you need specific event handlers, then you can set them up according
to the event you are listening on, and attach any number of like controls to
it.

Hope this helps.
 
That's what things like OnChange() are for, and as far as i know, you
have to do it to every control.

bool unchanged = true;

private void checkBox1_CheckedChanged(object sender, EventArgs e) {
unchanged = false;
}

that's probably how I'd do it. i'm new to C# tho. I'd do that for
every control on the form, by creating an updated() function that I
could call.
 
As someone stated on another forum, what I am looking for is a "Form IsDirty"
event. Any other ideas?

Thanks
Bill Zack
 
I know that this isn't what you asked... :) ...but I'm wondering: why
aren't you doing this in a model object, rather than in the form
itself? That's what I'm doing: underneath each form I have a
corresponding model, and the model tracks differences from the original
values, and informs the form (for example) whether to enable the Save
button.
 
Another (ugly) way would be to write your own (derived) version of each
type of control that implements an interface that defines properties
and methods to track changes: ResetDirty(), and IsDirty.

public interface ITracksChanges
{
void SetOriginalValue(object val);
bool IsDirty { get; }
}

Each derived control could then store its original value and compare
that against its current value. Then you use the derived controls in
all of your projects.

For the record, I dislike this solution. It's an ugly hack on the
WinForms framework, and using view / model would be a far better way to
go. I'm just offering it as a (hack) alternative.
 
Is there any reason why I could not use reflection at startup to walk down
the control hierarchy and set a common handler for any events that I am
interested in for that control type?
 
Back
Top