Changing TextBox Text as an Undo-able Action

The TextBox class supports undoing the last action–inherited from TextBoxBase.  Normally the user does this by pressing the undo key (Ctrl-Z if your keyboard doesn’t have a specific Undo key) or by selecting “Undo” from the context menu.  The last action can also be undone programmatically by calling TextBoxBase.Undo() (after calling CanUndo() to see if Undo() will work).


Changing the text in a TextBox so that the change can be undone is not so obvious though.  Changing the Text property or the SelectedText property is not undo-able.  .NET 2.0 added TextBox.Paste(String) (not inherited from TextBoxBase, it’s inherent to TextBox) that replaces the currently selected text and is undoable.  If you want to replace all the text while allowing the user to undo it, simply call TextBoxBase.SelectAll() before Paste(Sting).  For example:



textBox.SelectAll();


textBox.Paste(text);


This side-effect, unfortunately, is not documented–which is why it “is not so obvious”.

7 thoughts on “Changing TextBox Text as an Undo-able Action

  1. Excellent, this is just what i was looking for.

    Unfortunatly it doesn’t work on ComboBoxs, but after digging around, this has the same effect:

    comboBox.SelectAll();
    comboBox.SelectedText = text;

    (which doesn’t work on TextBoxs, go figure)

  2. I’m looking for just the opposite. I have a RichTextBox control, and I’d like to know how I can make some changes WITHOUT messing with the undo buffer. Something like

    SuspendUndoHistory()
    //DO some stuff
    ResumeUndoHistory()

    so that if I make changes in the middle, they won’t affect the undo buffer. These changes would be like inserting hidden text etc, and when I do it, the undo operation is no longer available, I assume because the rtb cannot undo the changes I did programmatically.

    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *