Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
tried many possible ways but none worked.
i need a code to make the back button go backwards to the last page (ex if i was on form 4 with multiple buttons that take you to many different forms. when i reach each form i need to be able to go backwards to the last form but not the form before. So if one button goes from form4 to form9 i need it to go back to form4.

the problem is that there are many buttons that will take you to form9 but i need to focus on the last button hit so the form goes back to the correct form.

What I have tried:

namespace backButtonTest
{
    public partial class Form1 : Form
    {
       

        public Form1()
        {
            InitializeComponent();
            
        }
         
        public static PrevPg()
        {
            Form1 cwForm1 = new Form1();
            Form2 cwForm2 = new Form2();
            Form3 cwForm3 = new Form3();

            Form1 cwFrom1 = new Form1();
            //this.Hide();
            cwForm1.Show();
        }
        private void button3_Click(object sender, EventArgs e)
        {
            if (cwForm1 == null)
            {
            }
        }

        
    }
}
Posted
Updated 19-Sep-22 5:40am

1 solution

There are a number of ways you can do this, but the easiest way to do this is to create a static Stack<Form> in the main app form. Each time you open a new form, add yourself to the Stack, and when the user clicks "back" you have the previous form ready to rock and roll.

This works provided forms aren't closed: if they are, they need to remove all instances of themselves from the Stack to prevent "already Disposed" errors.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900