ChathurawinD
ChathurawinD

Reputation: 784

how to close current form and open new form properly?

I'm trying to close current form and open main form in my login. I'm trying to do it as given in the accepted answer here. This is how I modified my Program.cs. Login form works ok. It opens login form. But when I logged in how to show main? How to use this dialog result in my login form to show main.

  static void Main()
    {

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        using (var login = new frmLogin())
        {
            if (login.ShowDialog() != DialogResult.OK) return;
        }

        Application.Run(new frmMainAdmin());  
   }

How can I achieve this Dialog result given in the above code in my login form? I really don't get it.

Here's how I perform login in my Login form. in a button click event.

        SqlDataReader reader = new loginUserOP().userLogin(txtUserID.Text, txtpwd.Text);
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    LoggedUserInfo.lguserfname = (String)reader[0];
                    LoggedUserInfo.lguserlname = (String)reader[1];
                    LoggedUserInfo.lgusercategory = (String)reader[2];
                    LoggedUserInfo.lguserloginid = (String)reader[3];
                    LoggedUserInfo.lguserid = (int)reader[4];
                }
                reader.Close();
                }

Upvotes: 0

Views: 161

Answers (1)

James
James

Reputation: 82096

The code you have is fine, and will work, the problem is you never give it a chance to work because you never close frmLogin.

When forms are shown via ShowDialog they rely on the DialogResult property being set in order for it to determine which action to take - a form will generally read this in from a button control on the form. You can set this at design-time, however, you need to validate before you set the result therefore you need to do something like

private void btnLogin_Click(object sender, EventArgs e)
{
    using (var reader = new loginUserOP().userLogin(txtUserID.Text, txtpwd.Text))
    {
        if (reader.HasRows)
        {
            while (reader.Read())
            {
                LoggedUserInfo.lguserfname = (String)reader[0];
                LoggedUserInfo.lguserlname = (String)reader[1];
                LoggedUserInfo.lgusercategory = (String)reader[2];
                LoggedUserInfo.lguserloginid = (String)reader[3];
                LoggedUserInfo.lguserid = (int)reader[4];
            }
            // remove the modal dialog and let the application start
            this.DialogResult = DialogResult.OK;
        }
    }
}

You should also notice that clicking the red X at the top right hand side of frmLogin kills the application, that's because DialogResult.Cancel is set automatically for you.

Upvotes: 1

Related Questions