How does stack.pop () work? I want to implement the Undo function

I write in the Stack text from the form when you change the text

private void Output_tb_TextChanged(object sender, EventArgs e) { undoActions.Push(output_tb.Text); } 

Here I return the text when you click Undo

 private void Undo_bt_Click(object sender, EventArgs e) { if (undoActions.Count<1) { return; } output_tb.Text = undoActions.Pop(); 

But the previous state of the text appears only when the second click on the Undo button. Why it happens?

    1 answer 1

    because the last value in the stack is the same as the current value in the textbox

     if (output_tb.Text != undoActions.Peek()) undoActions.Push(output_tb.Text); 
    • I used exactly this implementation of Undo, only for the KeyDown event in output_tb - and excellent - one character was deleted, but I need to implement Undo in case the text is not typed from the keyboard but inserted or generated. Tried through TextChanged, does not work - zKuYyPWdawUPvqN
    • I tried your answer, the compiler said that the stack is empty, I added undoAction.Push ("") to the MainForm constructor; but still there is no result after that. - zKuYyPWdawUPvqN