1

I want to open the second form in my app which I managed to do, but the first form is still opened in the background. How can I close it?

private void BtnLogin_Click(object sender, EventArgs e)
{
    var newForm = new Form2();
    if (string.Equals(txtbName.Text, "Georgi") && string.Equals(txtbPassword.Text, "123"))
    {
        newForm.Show();                
    }
    else
    {
        label2.Text = "Wrong password or username.Try again";
    }
}
haldo
  • 14,512
  • 5
  • 46
  • 52
gmatinski
  • 41
  • 8
  • 2
    Does this answer your question? [c# open a new form then close the current form?](https://stackoverflow.com/questions/5548746/c-sharp-open-a-new-form-then-close-the-current-form) – vmilojevic Dec 04 '19 at 12:12

3 Answers3

0

Try this:

this.Hide();

Or alternatively, you could use the name of the form you want to hide, as in:

YourForm.Hide();
0

Depends on whether you just want to hide the form or close it.

For closing you would want to go with:

private void BtnLogin_Click(object sender, EventArgs e)
{
    var newForm = new Form2();
    if (string.Equals(txtbName.Text, "Georgi") && string.Equals(txtbPassword.Text, "123"))
    {
        newForm.Show();   
        this.close(); 
    }
    else
    {
        label2.Text = "Wrong password or username.Try again";
    }
}

If you just want to hide it go with:

private void BtnLogin_Click(object sender, EventArgs e)
{
    var newForm = new Form2();
    if (string.Equals(txtbName.Text, "Georgi") && string.Equals(txtbPassword.Text, "123"))
    {
        newForm.Show();   
        this.Hide(); 
    }
    else
    {
        label2.Text = "Wrong password or username.Try again";
    }
}
0

Do you want to close or hide the first form when the second one is open?

In this solution, you hide the first form and close it if the second form is closing.

private void BtnLogin_Click(object sender, EventArgs e)
    {
        var newForm = new Form2();
        if (string.Equals(txtbName.Text, "Georgi") && string.Equals(txtbPassword.Text, "123"))
        {
            Form2 form = new Form2();
            this.Hide();
            form.FormClosed += (s, args) => Close();
            form.Show();            
        }
        else
        {
            label2.Text = "Wrong password or username.Try again";
        }
    }