Ken Wong
Ken Wong

Reputation: 23

C# - Failed to close an old form after a new form is shown

I'm creating a login function. After validating the password, the main form will be called. Here is the partial code:

Login.cs

private void btnLogin_Click(object sender, EventArgs e)
{
    //Interaction with Database
    Main.Show();
    this.Close();
}

As I expect only the Login form will be closed and the Main form will remain unchanged.

However both of them are closed after the last command is executed.

How can I fix this problem please ?

Upvotes: 0

Views: 228

Answers (4)

kostas ch.
kostas ch.

Reputation: 2035

In your program.cs put in Application.Run(main);

Then in main.load event open your login form using show dialog.

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Main());
}

and on main

public Main()
{
    InitializeComponent();
    Login p = new Login();
    DialogResult dr = p.ShowDialog();
    if (dr == DialogResult.OK)
    {
        //...
    }
    else
        Application.Exit();
}

Upvotes: 3

Ashigore
Ashigore

Reputation: 4678

If you open the Program.cs file you will see a command similar to this:

    Application.Run(new PasswordForm());

The form specified in this command is what ties the program into existence, when this form closes the STA Thread continues execution and then finishes, closing the whole application.

To fix this, create an instance of you password form and do all that in the Program.cs file before calling Application.Run on the main UI form.

Upvotes: 0

Prashant16
Prashant16

Reputation: 1526

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

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

    // close application
    this.Close();
}

Upvotes: 0

yclkvnc
yclkvnc

Reputation: 933

If you close your main Form, application terminates. Instead of closing, you can hide your main Form with :

this.Hide();

Upvotes: 0

Related Questions