Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undo feature for Textbox

Tags:

c#

winforms

I'm working on a very simple Undo feature for a TextBox and I've got a weird problem. When I try to take strings from the Stackthat holds all the changes and put them inside the Textbox I don't see any changes.

I made a little Debug Label to check if this is really working or not. I found out that it is working in the label, but in the Textbox it uses its own Undo functions.

Is there a way to cancel or override the Textbox Undo and use my own function?

Here is sample code from the change I made:

 private void Form1_KeyDown(object sender, KeyEventArgs e)
        if (e.KeyCode == Keys.Z && (ModifierKeys & Keys.Control) == Keys.Control)
            {
                nameTextBox.Text = undoName.GetLastChange(); //--> not working

                undoDebuglabel.Text = undoName.GetLastChange(); --> working
            }
}

The GetLastChange() is getting the info from a Stack inside the class.

It's like the Textbox is not letting me to see the changes. Could it be because I'm using the same shortcut, CTRL + Z to do it?

like image 697
samy Avatar asked Oct 20 '12 17:10

samy


2 Answers

Clear the Textbox's own stack by using the ClearUndo method. Try this:

nameTextBox.ClearUndo();
nameTextBox.Text = undoName.GetLastChange();
like image 66
keyboardP Avatar answered Oct 10 '22 21:10

keyboardP


You can create your own TextBox to handle history by inheriting from System.Windows.Forms.TextBox. Take a look at my sample:

public class HistoryTextBox: System.Windows.Forms.TextBox
{
    bool ignoreChange = false;
    List<string> storage = null;


    protected override void OnCreateControl()
    {
        base.OnCreateControl();
        //init storage...
        storage = new List<string>();
    }

    protected override void OnTextChanged(EventArgs e)
    {
        base.OnTextChanged(e);
        //save change to storage...
        if (!ignoreChange)
        {
            storage.Add(this.Text);
        }
    }

    public void Undo()
    {
        if (storage.Count > 0)
        {
            this.ignoreChange = true;
            this.Text = storage[storage.Count - 1];
            storage.RemoveAt(storage.Count - 1);
            this.ignoreChange = false;
        }
    }
}

Everytime you need to undo just call:

historyTextBox1.Undo();

This class will give you multiple histoy records.

like image 34
Gregor Primar Avatar answered Oct 10 '22 20:10

Gregor Primar