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

1.8k views Asked by At

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();
}
1

There are 1 answers

3
Sudhakar Tillapudi On

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();