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
Cody gray
source share