Ljupce Anastasov
Ljupce Anastasov

Reputation: 54

Can't hide or close form after switching to another form

I'm trying to switch Windows forms after successful login at the login form, I move to the main form. The problem is once the user logs in by clicking the login button, the main form opens but the login forms stays in the background, won't go away. I tried this.hide() and this.close, but they don't work. Here's some of the code from the btnLogin event...

        //connection to access database and checking if the user exist, ...
        ...
        if (!rdr.Read())
        {
            MessageBox.Show("Wrong username or password.");

        }
        else 
            GlobalClass.GlobalVar = true;
            GlobalClass.GlobalStr = rdr["user"].ToString();
            MainScreen _main = new MainScreen();
            _main.ShowDialog();

        rdr.Close();
        conn.Close();
        this.Close();

    } 

Upvotes: 2

Views: 1600

Answers (3)

Edper
Edper

Reputation: 9322

You can hide() then close() but you have to use an event in doing so and like others suggest I will use Show() method instead of ShowDialog().

I would probably declare globally the Main form first.

MainScreen _main;

Then when you are about to show the Main after login use event to Hide() the login Form and then an event to Close() login form once Main form is closed.

GlobalClass.GlobalVar = true;
GlobalClass.GlobalStr = rdr["user"].ToString();
_main = new MainScreen();
_main.Load += new EventHanlder(_main_Load);
_main.FormClosed += new FormClosedEventHandler(_main_FormClosed);
_main.Show();

Catch the event for Main Form loading to Hide the Login form, like:

private void _main_Load(object sender, EventArgs e)
{
    this.Hide(); // Hides Login but it is till in Memory
}

Catch the event for Main Form closing to Close the Login form, like:

private void _main_FormClosed(object sender, FormClosedEventArgs e)
{
    this.Close(); // Closes Login and remove this time from Memory
}

Upvotes: 0

Selman Genç
Selman Genç

Reputation: 101680

you are using ShowDialog use Show method instead, here:

_main.Show();

When you use ShowDialog your program waits until you close your MainForm and doesn't go to the next line.So your second form doesn't close until you close the MainForm.

Upvotes: 1

Chris Ballard
Chris Ballard

Reputation: 3769

It's probably better to create and display the main form from Program.cs, and then show and dispose the LoginDialog from the OnLoad handler of the main form.

In particular if LoginDialog is created from Application.Run then closing it will exit the app, so not very useful that way around.

Upvotes: 0

Related Questions