0

I want to know how the best way to close current C# form and open another one

DetailForm df = new DetailForm();
df.Show();
this.Hide();
this.Dispose();
Paul Annetts
  • 9,554
  • 1
  • 27
  • 43
user2519850
  • 97
  • 1
  • 1
  • 6

1 Answers1

14
DetailForm df = new DetailForm();

df.Show();

this.Close();

But be careful, if you close the main form the application will be closed.

EDITED

To run this if the first form is the main form you need do more. Try something like this:

Change your Program.cs file to this:

public static class Program
{
    public static bool OpenDetailFormOnClose { get; set; }

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        OpenDetailFormOnClose = false;

        Application.Run(new MainForm());

        if (OpenDetailFormOnClose)
        {
            Application.Run(new DetailForm());
        }
    }
}

And in the main form, close it with this:

private void Foo(object sender, EventArgs e)
{
    Program.OpenDetailFormOnClose = true;

    this.Close();
}

If you set OpenDetailFormOnClose with true after the close of the main form, the DetailForm will be call.

Jonny Piazzi
  • 3,684
  • 4
  • 34
  • 81