简体   繁体   中英

How to go back to the previous form in c#?

I've been looking for a way to go back to the previous form in c#. I am building a Bike Builder program, and basically it let you view your desired parts, and go back to previous form and edit your shopping cart.

Form 2 will be the Shopping form, where you can select/deselect your product. Form 3 will be a review form, it will display how many parts you have been put in your cart so far, display the total. In form 3, there will be a button called "BACK", it will let you to go back to form 2 and update your cart.

// This is form 2
public partial class frmSelectParts : Form
{
// variables and functions
// .......

    public frmSelectParts()
    {
        InitializeComponent();
        this.WindowState = FormWindowState.Maximized;
    }
}

//This is form 3
public partial class frmYourCart : Form
{
    public frmYourCart()
    {
        InitializeComponent();
        this.WindowState = FormWindowState.Maximized;            
        cbbShipping.Items.Add("Standard 5 - 10 days");
        cbbShipping.Items.Add("Express 3 - 5 days");
        cbbShipping.Items.Add("Over night 1 day");
    }
}

You could do as Justin has suggested and Close or you could use frmYourCart.Hide() and frmSelectParts.Show() . Using Close will result in frmSelectParts form being shown, it depends on whether you would like to keep their changes there hidden.

It's not exactly what you asked for but.. if it's possible, you could create only one form and add a TabControl. Then you can have one tab for each task.

The user could go back by using the tab headers or you can still have your back button and use the SelectTab() method to show the previous tab.

To avoid having more than one back button, you could place it just before the TabControl on your form. On the click event of the back button you would do :

    if (tabControl.SelectedIndex > 0) // Higher than first tab
       tabControl.SelectTab(tabControl.SelectedIndex - 1);

If I were you, I would simply call the .Show() method on the form that you want to show and then .Hide() (or .Close() ) on the form you are leaving.

Shopping Form:

private void btnReview_Click(object sender, EventArgs e)
{
   reviewForm frmReview = new reviewForm();
   frmReview.Show();
   this.Hide();  // You could also call this.Close() instead.
}   

Summary Form:

private void btnBack_Click(object sender, EventArgs e)
{
   frmSummary frmSummary = new frmSummary();
   frmSummary.Show();
   this.Hide();  // You could also call this.Close() instead.
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM