How do I close the form I’m in?

Asked

Viewed 737 times

2

private void BtnEntrar_Click(object sender, EventArgs e)
    {
        string login = txtLogin.Text;
        Conta conta = new Conta();
        try
        {
            BLL bll = new BLL();
            conta = bll.SelectContaByLogin(login);
            if(txtSenha.Text == conta.Senha)
            {
                TelaDeLogin form1 = new TelaDeLogin();
                form1.Close();
                TelaInicial form2 = new TelaInicial();
                form2.ShowDialog();

            } else
            {
                MessageBox.Show("Login ou senha incorretos.");
            }
        }
        catch(Exception ex)
        {
            throw ex;
        }
    }

I’m doing a Login and Password system in Visual Studio with C#, and I need to close the form Login when the user logs in.

The part about opening the form Home Screen works, but the form1.Close() does not work. I tried Hide(), tried this.Close(), but it’s not closing either.

  • this.Hide() doesn’t work?

  • Do me a favor. If none of the answers to the below solve your problem post event code onClose form TelaDeLogin .

4 answers

1

It does not close due to ShowDialog()

private void BtnEntrar_Click(object sender, EventArgs e)
{
    string login = txtLogin.Text;
    Conta conta = new Conta();
    try
    {
        BLL bll = new BLL();
        conta = bll.SelectContaByLogin(login);
        if(txtSenha.Text == conta.Senha)
        {
            this.Hide();
            TelaInicial form2 = new TelaInicial();
            form2.Show();

        } else
        {
            MessageBox.Show("Login ou senha incorretos.");
        }
    }
    catch(Exception ex)
    {
        throw ex;
    }
}

0

Close with:

form1.Dispose();

This will shut down the instance for good.

0

I do so and it works well:

Hide(); 
using (var homeScreen = new MdlHomeScreen())
{
  homeScreen.Closed += (s, args) => Close();
  homeScreen.ShowDialog();
}

-3

Fastest way:

Application.OpenForms[1].Close();

The number inside the square bracket is the form you want to close...

  • 1

    That doesn’t close the Form open. If you have more than one Form opened, you can close the wrong one. And if you only have one, one IndexOutOfRangeException will be caused.

  • It would be better to pass the parameter Form.Name at the beginning of a numerical index.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.