How to prevent the form of being closed when AcceptButton is pressed in C#

117 views Asked by At

I have a Form which has an “Ok” Button that is assigned as AcceptButton. When I click this Button or press Enter key the Form is automatically closed, as expected. Under the event OkButtonClick I wrote a routine to check if all the fields were correctly filled, case not an error message is thrown through a MessageBox. The problem is that after close the MessageBox the Form is automatically closed, but I would like it remains opened to allow user to correct his inputs. In this case, how should I do to prevent that Form was closed?

1

There are 1 answers

0
Steve On BEST ANSWER

In that click event, if your validation fails, add this line

 this.DialogResult = DialogResult.None;

The inner working is more or less the following:

The general rule is that the form engine automatically closes a form if its DialogResult property is set to anything but DialogResult.None.

When a form's engine receives a click on a button, the engine sets the forms DialogResult property to the value present on the button's DialogResult property, then calls the event handler. If you do nothing, at the exit of the event handler the engine looks at the forms DialogResult property and reacts accordingly. So you need to set the DialogResult back to None if you want to counteract the default behavior.