Search code examples
c#visual-studioback-button

C# Back button on visual studio


I am creating a quiz for my As level coursework on visual studio 2019(c#). In this I will be creating a help button that will have information that the user may need if they are stuck. The button to access the help form will be avaliable through a menu strip bar loacted in the top corner of every form. In the help form there will be a menu strip bar with a back button. I would like to know how to code a back button to go back to the previous form eg Question 1-10 forms or the login form. I know how to code it if i wanted to back to a specific form but it is the fact it may need to back to any form as i dont know which form the user will have previously been on.


Solution

  • If you want to code a back button to go back to the previous form, you can refer to the following code:

    Code in Form1.cs:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            
        }
        private void btnForward_Click(object sender, EventArgs e)
        {
            this.Hide();
            Form2 newform =  new Form2();
            newform.ShowDialog();
            this.Show();
        }
    }
    

    Code in Form2.cs :

    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
        
        private void btnForward_Click(object sender, EventArgs e)
        {
            this.Hide();
            Form3 newform = new Form3();
            newform.ShowDialog();
            this.Show();
        }
        private void btnBack_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
        }
    }
    

    Code in Form3.cs :

    public partial class Form3 : Form
    {
        public Form3()
        {
            InitializeComponent();
        }
        
        private void btnForward_Click(object sender, EventArgs e)
        {
            this.Hide();
            Form4 newform = new Form4();
            newform.ShowDialog();
            this.Show();
        }
        private void btnBack_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
        }
    }
    

    If you want to open other forms, just change this code ‘Form2 newform = new Form2();’.enter image description here