“Exit to sub” on the DialogResult.OK button

I have a VB.NET form (CopyScenarioForm) with an OK button (DialogResult = OK property), and also assigned as a “accept button” for the form.

I am showing this form from my main form (mainForm) using

If DialogResult.OK = CopyScenarioForm.ShowDialog() Then DoSomething() End if 

Now, when the user clicks the CopyScenarioForm.OK button, I want to check his records, and if this is not valid, I want to "Exit Sub" from the OK button click handler, but when I do this, the form still closes and DoSomething () is executed. Is there a way to stop this and keep the form alive and only exit if the inputs are valid. I noticed that if I changed the “OK” property of DialogResult to “NONE” instead of “OK”, this would not close it. but how do you know how the user exited the form to do DoSomething ().

+3
winforms
source share
2 answers

What happens when, when creating the DialogResult button, it is set to “OK” in the designer, this value is set each time the “OK” button is pressed, no matter what. Therefore, even when you exit the event handler using Exit Sub , the calling form sees DialogResult as "OK."

As you discovered, you first need to set the DialogResult property to "None" in the constructor, and then process the setting of the DialogResult property to the correct value manually in your click on the "OK" button handler. For example:

 Private Sub OKButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) If EntriesAreValid Then 'Return OK to the calling form Me.DialogResult = DialogResult.OK Else 'Show an error message, but keep the form open MessageBox.Show("One or more of your entries were invalid.") End If End Sub 

Alternatively, you can leave the DialogResult property set to OK in the constructor and simply override it whenever the test fails by setting it to No. This probably creates cleaner code:

 Private Sub OKButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) If Not EntriesAreValid Then 'Show an error message MessageBox.Show("One or more of your entries were invalid.") 'Clear the DialogResult property and keep the form open Me.DialogResult = DialogResult.None End If End Sub 
+6
source share

Install it from your code if everything is verified.

 DialogResult = DialogResult.OK 
0
source share

All Articles