Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undoing Changes in Bound Objects with C#

In my application I have a collection of data objects that define what types of data the application collects as it executes.

The user can open a dialog window to edit these objects and that dialog window contains DataGridView instances that are bound to the collections. This means that any changes the user makes are instantly applied, which is not good.

The other issue is that this dialog window has a Cancel button allowing the user to discard all the changes they have made since opening the window.

Currently when the window is opened I serialize all the objects (shallow copy won't work) and if the user clicks on Cancel then I deserialize them to restore them. The problem I am running into is that this is messy. It changes all the references and some of these objects store a data history as well, which isn't serialized. I then have to have events rippling out through the application to notify objects to update their references, etc. It's a pain.

Is there a better approach to this problem?

like image 788
Andy Avatar asked Oct 11 '22 12:10

Andy


1 Answers

There is a better way, using an interface that is cooked into the framework - IEditable

BeginEdit
CancelEdit
EndEdit

The basic idea it that you create a snapshot of some object's state when you call BeginEdit. On CancelEdit, you roll back to that SavedState, and on EndEdit you commit it.

The devil is in the details of course. Here's a popular link that has served as an implementation answer to similar SO questions for some ideas

http://www.paulstovell.com/blog/runtime-ui-binding-behavior-ieditableobject-adapter

Cheers,
Berryl

NOTE: this isn't conceptually different to what tocco is saying, and you should give him the answer. BUT worth spelling out in a separate answer because it formalizes the concept in a .Net idiomatic way and offers more insight into a useful implementation. Besides, it is good fun saying the word idiomatic :--)

like image 55
Berryl Avatar answered Oct 16 '22 10:10

Berryl