简体   繁体   中英

C# If have 3 Form , Can I show Form3 and close Form1 and Form2?

I have 3 Form. I want to show Form3 and close Form1, Form2 when click button in Form2 . This is my code . when I run this code it can show Form3 but not close Form1 .

Form1

private void button1_Click(object sender, EventArgs e)
{
    Form2 frm2 = new Form2();
    frm2.ShowDialog();
    //frm2.Show();
}

Form2

private void button1_Click(object sender, EventArgs e)
{
    Form3 frm3 = new Form3();
    Form1 frm1 = new Form1();
    frm3.Show();

    frm1.Hide();  // It not close Form1
    this.Hide();
    // frm1.Close();
    // this.Close();
}

Problem : You are creating the newinstance of Form1 and then trying to close/hide it.

Solution: You need to get the Form1 instance which was already in Memory and then hide or close it.

Replace This:

Form1 frm1 = new Form1();
frm1.Hide();  // It not close Form1

With This:

Form1 form1 = (Form1) Application.OpenForms["Form1"];
Form3 frm3 = new Form3();
frm3.Show();   
form1.Hide();

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