Svish Svish - 11 months ago 68
C# Question

How to implement good and efficient undo/redo functionality for a TextBox

I have a TextBox which I would like to implement undo/redo functionality for. I have read that it might have some slight undo functionality already, but that it is buggy? Anyways, I would like to implement both undo and redo functionality also just to learn how you would go ahead and do that.

I have read about the Memento Pattern and looked some on a Generic Undo/Redo example on CodeProject. And the pattern kiiind of makes sense. I just can't seem to wrap my head around how to implement it. And how to do it effeciently for the contents of a


Of course I could just store
, but that would hug up quite a lot of memory pretty fast, especially if the
contained a lot of text.

So anyways, I'm looking for some advice on how to implement a good, clear and efficient way of implementing this functionality. Both in general and especially for a TextBox c",)


The .NET System.ComponentModel namespace comes with an IEditableObject interface, you could also use INotifyPropertyChanging and INotifyPropertyChanged. MVC Pattern would also make it that your interface responds to changes in the model through events thus updating or restoring the value of your textbox.

Effectively the Memento Pattern.

Have you had a look into these? Here is a how to.

A simple and quicker version would be to store the state of the textbox OnTextChanged. Each undo would return the last event in an Array. The C# Stack Type would be handy here. You could clear the state once you are off the interface also or after Apply.