3
votes

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
In your program.cs file I'd imagine its opening the real form 1, "It not close form1" because youve just created an instance of form1 that is never opened. If program.cs is opening form1 then no, you cannot close this as you are expectingSayse

1 Answers

6
votes

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