Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing a form and then call another one

Tags:

c#

forms

winforms

I want to close the current form I'm on (MainForm) and then opening a second one (Form).

I've tried:

private void buttonStartQuiz_Click(object sender, EventArgs e)
{
    this.Close();

    Form2 form2 = new Form2();
    form2.ShowDialog();
}

Or adding the this.Close(); after form2.ShowDialog() also doesn't work.

Any hints?

EDIT: Might as well add that by adding this.Close() after form2.ShowDialog() it close only when I close the new form. If I choose form2.Show() instead it immediately closes both of the forms.

like image 227
elvispt Avatar asked May 01 '10 18:05

elvispt


People also ask

How do I close a single form in C#?

The Form. Close() function is used to close a Form in a Windows Form application in C#. We can use the Form. Close() function inside the button click event to close the specified form by clicking a button.

Does form close call Dispose?

After you close the form by Close or by clicking on X, it will be disposed automatically.

What is the code to close a current active form?

Form2 nextForm = new Form2(); this. Hide(); nextForm. ShowDialog(); this. Close();


1 Answers

Change

this.Close();

To:

this.Hide();

Because you can't Close Main Application window and want to application runs after it. You must hide main form or change main window to window who was still opened.

In this case you must close main window after ShowDialog() was ended. Then you must add on the end of this button event function this.Close()

Your code new code is:

private void buttonStartQuiz_Click(object sender, EventArgs e)
    {
        // hide main form
        this.Hide();

        // show other form
        Form2 form2 = new Form2();
        form2.ShowDialog();

        // close application
        this.Close();
    }
like image 117
Svisstack Avatar answered Sep 26 '22 15:09

Svisstack