简体   繁体   中英

Closing Multiple Forms in C#

I have total 3 forms (Form1, Form2 and Form3) in my Windows Forms Application.

Form2 is log-in page. When user clicks on sign-in button in Form1, Form2 must be open and if user provides accurate username and password then Form3 is needed to open and to close both Form1 and Form2.

How to code such thing in C#? I am using Microsoft Visual Studio 2012.

So far I have done following procedure:

double click the Form1 to get at the coding window and wrote-

Form2 secondForm = new Form2();

Just outside of the Form Load event

& inside the button, i wrote-

secondForm.Show();

So when I run the solution, Form2 is opened by clicking a button in Form1 (Works Perfectly!). But I have no idea how to close Form1 and Form2 when user enter correct username and password combination in Form2 to open Form3.

Form1 firstForm = new Form1();
firstForm.Close();

isn't closing the form.

Please guide me.

You should add a new Class with a Main() method. (OR) There will be Program.cs in your project.

And, start the application from the Main() method. You can change "Startup object:" property of your project to "<YourApplicationName>.Program".

You Main() method should show Form1 and Form2 as Dialog.

If DialogResult is OK then run the Form3 by Application.Run() method.

DialogResult r;
r = (new Form1().ShowDialog());
if( r == DialogResult.OK )
Application.Run(new Form3());

You cannot close the main form (the one that you used to start the message loop) if you do that will end/close the entire application. What you can do however instead is this:

Form1 code

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var f2 = new Form2();

        var res = f2.ShowDialog();

        if (res == DialogResult.OK)
        {
            var f3 = new Form3();
            this.Visible = false;
            f3.ShowDialog();
            this.Close();
        }
    }
}

Form2 code:

public partial class Form2 : Form

    {
        public Form2()
        {
            InitializeComponent();
        }

        private void buttonLogin_Click(object sender, EventArgs e)
        {
            // if username and password is ok set the dialog result to ok
            this.DialogResult = DialogResult.OK;

            this.Close();
        }
    }

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