Maria João
Maria João

Reputation: 189

Control changes in a Windows Forms C# application

I have a form with several components, like TextBox and ComboBox, and I need to know when click in the out button if there was any changes in the form. Is there a way to do this?

Upvotes: 3

Views: 2634

Answers (4)

pezi_pink_squirrel
pezi_pink_squirrel

Reputation: 774

If this is already nearly finished, and you need something quick it's probably going to be easier to just always assume that something has changed, then in your update logic afterwards (whatever it's doing) don't update stuff that is still the same.

As someone else mentioned, it's very possible for someone to change something, then change it back. What would you want to do in that case? You won't be able to maintain a proper dirty state of the form without a fair bit of additional work.. this is something that you need to plan for before you start, really.

Upvotes: 0

ng5000
ng5000

Reputation: 12580

You could loop through all controls but this would have to be recursive because a control can contain controls, e.g. (no null checks for brevity):

private void IterateOverControls( Control parent )
{
    ProcessControl( parent );

    foreach( Control control in parent.Controls )
        IterateOverControls( control );
}

In ProcessControl you could hook up event handlers to handle OnEnter (to store the state) and OnLeave (to check the current state against the stored state). You'd need to unhook all the event handlers when disposing. Also, the code to store check the state would have to change for different control types, e.g. TextBox would be the Text property, but a radio button would be an index, etc. Obviously this becomes simpler if you can compare form state to your underlying data store state, in which case you can just make the comparison on each OnLeave event.

One thing also to consider is do you need to track real changes? For example, I have 2 radio buttons: A and B. I check B (a change), so the out button or whatever has its Enabled property changes. I then click on A (i.e. back to my original state). Do you need to revert the button at that point?

This is why you should look towards a model view controller approach :)

Upvotes: 1

Luke
Luke

Reputation: 3017

You could create a generic change event handler which sets a flag on change, and then assign all the controls' Change events to it.

This could probably be done pretty easily by looping through all of your controls onload.

Upvotes: 3

mqp
mqp

Reputation: 71945

The easiest way to do this would be to simply use a variable on the form named something like "IsChanged." Set it false when the form is initially displayed, and set it true if they make any changes.

Alternately, you could record the values of everything when the form is displayed, and when they finish, check the current values against the old ones to see if anything changed.

Upvotes: 0

Related Questions