1

So let's say I clicked a button and it's supposed to open a new form and close the current form.

private void button1_Click(object sender, EventArgs e)
{
    this.Close();
    Form2 AFormInstance = new Form2();
    AFormInstance.Show();
}

I tried this.Close() but what ended up happening was both forms closed. How do I open Form2 and close Form1?

puretppc
  • 3,146
  • 7
  • 35
  • 63

2 Answers2

0

If the parent of Button1 is Form1 you can use :

var formToBeClosed = ((sender as Button).Parent) as Form;
formToBeClosed.Close();
-2

Just switch some lines:

private void button1_Click(object sender, EventArgs e)
{
    Form2 AFormInstance = new Form2();
    AFormInstance.Show();
    this.Close();
}

Edit: On further thought: aren't you accidentally closing your main form?

Change the default code of program.cs to:

    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Form1 form1 = new Form1();
        form1.Show();
        Application.Run();
    }

To close the application use:

Application.Exit();
Jef Patat
  • 959
  • 1
  • 9
  • 24