Prevent ShowDialog() from returning when OK button is clicked

user1151923 picture user1151923 · Apr 26, 2012 · Viewed 29.1k times · Source

I have a dialog that I want to prevent from closing when the OK button is clicked, but it returns, and that even if the AcceptButton property is set to none instead of my OK button. What is the best way to stop it from closing?

Answer

David Heffernan picture David Heffernan · Apr 26, 2012

In fact you are changing the wrong property. You certainly do want AcceptButton to be the OK button. This property determines which is the default button in Windows terms. That is the button which is pressed when you hit ENTER on your keyboard. By changing AcceptButton you are simply breaking the keyboard interface to your dialog. You are not influencing in any way what happens when the button is pressed.

What you need to do is set the DialogResult property of your button to DialogResult.None since that's what determines whether or not a button press closes the form. Then, inside the button's click handler you need to decide how to respond to the button press. I expect that, if the validation of the dialog is successful, you should close the dialog by setting the form's DialogResult property. For example

private void OKbuttonClick(object sender, EventArgs e)
{
    if (this.CanClose())
        this.DialogResult = DialogResult.OK;
}