Search code examples
c#stringback

How can i go back previous observed string


Example

String context = string.Emty;

private void BtnForward_Click(object sender, RoutedEventArgs e)
{
  //First Click
  context = Abcd;
  TextboxText.Text = context; //Abcd 
  //Second Click
  TextboxText.Text = context; //new context = SADASD
  //Third Forth Fift click new string context
}

//Now how i can go back 5th string 4th string 3 2 1th string 
private void BtnBack_Click(object sender, RoutedEventArgs e)
{
  //Fift Forth Third Second First Observed string will show in the textbox
  // Reverse back previous string with sequence 
  TextBoxText.Text = context; // Will reverse/Go back in sequence 
}

How can i go back string

Even going forward forward string or and reverse back back . My english was not good enough to explain but if you are unable to understand what i was said please let me know


Solution

  • You need to keep references of the previous values. One approach is to keep a stack of strings where you push in the new value each time you hit BtnForward_Click() and pop (the most recent one) when you hit BtnBack_Click(). An example is given below:

        Stack context = new Stack();
    
        private void BtnForward_Click(object sender, RoutedEventArgs e)
        {
            // Here you would need to set the value of the Abcd based on your business logic
            context.Push(Abcd);
        }
    
        private void BtnBack_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                TextBoxText.Text = context.Peek(); // gets the most recently entered value of the stack that has not been removed (popped)
                context.Pop();                
            }
            catch (InvalidOperationException exc)
            {
                // Nothing to go back to
            }
        }