[C#] Close a form

Joined
May 11, 2008
Messages
722
Reaction score
50
I added
Code:
                Form2 f = new Form2();
                //this.Close();
                f.Show();
                this.Close();
in the button click
And it doesn't close
but the other form shows up

I tried this too
Code:
public Form2()
        {
            InitializeComponent();
            Form1 f = new Form1();
            f.Close();
        }
In the Form2 class, still didn't work
and I also tried
Code:
private void Form2_Load(object sender, EventArgs e)
        {
            Form f1 = new Form1();
            f1.Close();
        }
Didn't work.

Help me please (:
 
Ok sorry for the double post but I got the solution.

Code:
private void Form1_Load(object sender, EventArgs e)
        {
            Form2 WEEEEEES = new Form2();
            WEEEEEES.ShowDialog();
            this.Hide();    
        }

Add that on the form load.

Now make an event for form closing on the second form so it should look like this.

Code:
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }

and that should close the whole program when you close form 2
 
Kay
Code:
 private void button1_Click(object sender, EventArgs e)
        {
Form2 WEEEEEES = new Form2();
                WEEEEEES.ShowDialog();
                this.Hide();   
}
Didn't work for me.
 
What is the best way do a login screen? I have the Main() method in my
login screen. After iit checks the userid and password the OK button
loads the main application form but the next line is frmLogon.Close()
which closes the whole application! If I hide it, the app does not
close completely. Thanks.:?:
 
You can use DialogResult. So for example, in your main form, create and show the login form before InitializeComponent and use DialogResult to get the result as to whether to create the form or close the application

Code:
public Main()
{
    Login loginForm = new Login();

    if (loginForm.ShowDialog() != DialogResult.OK)
        Environment.Exit(0);

    InitializeComponent();
}

There's probably a better way than Environment.Exit(0) but I'm not experienced with WinForms as I use WPF.

So then with the Login form, as an example, you can have 2 buttons (one OK and one Abort). Create a click event for OK and use

Code:
private void OK_Click(object sender, EventArgs e)
{
    DialogResult = DialogResult.OK;

    Close();
}

with Abort, do the same except use Abort as the DialogResult like so (the DialogResult.Abort does not have to be there as we're checking if the DialogResult doesn't equal OK and by default Close() returns DialogResult.Cancel, in my opinion it's just easier to read)

Code:
private void Abort_Click(object sender, EventArgs e)
{
    DialogResult = DialogResult.Abort;

    Close();
}

So then now it will only continue to create the main form if the login form returns DialogResult.OK. If you've got any questions, feel free to ask.
 
Back