captonssj
captonssj

Reputation: 311

'Exit Sub' on DialogResult.OK button

I have a VB.NET form (CopyScenarioForm) with a OK button (DialogResult property = OK ) and also assigned it as Accept Button for the Form.

I show this form from my main Form (mainForm) using

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

Now when user clicks on the CopyScenarioForm.OK button, I want to validate his entries and if invalid I want to Exit Sub from the OK button's click handler but when I do that the form still closes out and DoSomething() gets executed. Is there a way to stop this and keep the form alive and only exit if the inputs are valid. I noticed, if I change the OK button's DialogResult property to NONE instead of OK then it doesn't cause it to close. but then how Do I know how the user exited the form to execute DoSomething()?.

Upvotes: 3

Views: 7920

Answers (2)

Cody Gray
Cody Gray

Reputation: 244752

What's happening is that when you have the button's DialogResult property set to "OK" in the designer, this value is set every time the OK button is clicked, no matter what. So even when you exit from the event handler early using Exit Sub, the calling form sees a DialogResult of "OK."

As you discovered, you'll first need to set the button's DialogResult property to "None" in the designer, and then handle setting the DialogResult property to the correct value manually in your "OK" button's click event 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 could leave the DialogResult property set to "OK" in the designer, and just override it whenever validation fails by setting it to "None". This probably produces cleaner code—to wit:

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

Upvotes: 6

Jonathan Wood
Jonathan Wood

Reputation: 67193

Set it from your code if everything checks out.

DialogResult = DialogResult.OK

Upvotes: 0

Related Questions