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?
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 :--)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With