Majid
Majid

Reputation: 14253

How to prevent modal dialog form to close after pressing OK?

I have a (login) form that use it as modal like this (parent form code):

using (var login = new Login())
{
     login.ShowDialog();
}

I do some checks on opened modal dialog and I want that it not close on pressing OK button if user name and password was wrong.

My login:

private void goSignIn_Click(object sender, EventArgs e)
{
     var loggedInCustomer =LoginController.signIn(usernameBox.Text, passwordBox.Text);
     if (loggedInCustomer == null)
     {
         MessageBox.Show("Wrong username or password! :( ", "Wrong!");
     }
     else
         Close();
}

Upvotes: 1

Views: 3487

Answers (3)

Dan
Dan

Reputation: 1080

Check the button (goSignIn) DialogResult property. If it's set, it automatically close the form.

If the DialogResult for this property is set to anything other than None, and if the parent form was displayed through the ShowDialog method, clicking the button closes the parent form without your having to hook up any events. The form's DialogResult property is then set to the DialogResult of the button when the button is clicked.

MSDN Button.DialogResult Property

Upvotes: 3

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73462

I guess you've set the DialogResult of goSignIn button to some value(probably DialogResult.OK), remove that line, everything should work fine as expected.

Upvotes: 3

Kristian Hebert
Kristian Hebert

Reputation: 357

Don't call close then

private void goSignIn_Click(object sender, EventArgs e)
{
  var loggedInCustomer =LoginController.signIn(usernameBox.Text, passwordBox.Text);
  if (loggedInCustomer == null)
  {
     MessageBox.Show("Wrong username or password! :( ", "Wrong!");
  }
  else
  {
     Close();
  }
}

Upvotes: 0

Related Questions