How do you stop a DialogResult OK button from executing using code?

emaduddeen

Well-known member
Joined
May 5, 2010
Messages
171
Location
Lowell, MA & Occasionally Indonesia
Programming Experience
Beginner
Hi Everyone,

I have a button with DialogResult OK set.

I'm using the following code to try and do validation:

VB.NET:
    Private Sub ButtonSaveChanges_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles ButtonSaveChanges.Validating

        If String.IsNullOrEmpty(EditBoxLastName.Text) Then
            MessageBox.Show("Please enter a customer name.", _
                            "Entry Error", _
                            MessageBoxButtons.OK, _
                            MessageBoxIcon.Exclamation)

            e.Cancel = True
        Else
            If SaveCustomerToDatabase() = True Then
                SaveCustomerRelativeToDatabase()
            End If
        End If
    End Sub

This code was originally in the Click event of the button but in the Click event I discovered e.Cancel does not work so I put the code in the Validating event.

The problem I now face is that the code never gets touched because the DialogResult OK is executing before the Validation event is touched.

Is there a way to stop DialogResult OK from executing based on my code?

Thanks.

Truly,
Emad
 
Your code is very wrong I'm afraid. First, you don't handle the Validating event of the Button. It's not the Button you want to validate. You want to validate the TextBox, so you handle the Validating event of the TextBox. In the Validating event handler of the TextBox you want only this part:
VB.NET:
        If String.IsNullOrEmpty(EditBoxLastName.Text) Then
            MessageBox.Show("Please enter a customer name.", _
                            "Entry Error", _
                            MessageBoxButtons.OK, _
                            MessageBoxIcon.Exclamation)

            e.Cancel = True
        End If
In the Click event handler of the Button you want to force the Validating event of the TextBox to be raised, to ensure it gets validated even if it hasn't received focus. You do that by calling ValidateChildren on the form. That returns False if one or more controls fail validation:
VB.NET:
If Me.ValidateChildren() Then
    'Validation passed so save.
End If
 
Back
Top