Code: Overriding Control Validation on Windows Forms in the Closing Event (Visual Basic)
This example shows how to close a form even if there is validation logic in the form and one or more of the controls contain invalid data. In the example, there is validation logic for a TextBox control. Validation is overridden in the form's Closing event.
Private Sub TextBox1_Validating(ByVal sender As Object, _ ByVal e As System.ComponentModel.CancelEventArgs) _ Handles TextBox1.Validating If TextBox1.Text.Length < 8 Then ("Value you entered is not valid;" _ & " it must be at least 8 characters.") e.Cancel = True End If End Sub Private Sub Form1_Closing(ByVal sender As Object, _ ByVal e As System.ComponentModel.CancelEventArgs) _ Handles MyBase.Closing e.Cancel = False End Sub
Compiling the Code
This project requires:
- A reference to the System namespace.
- A Windows Form.
- A TextBox control named TextBox1.
- Another control on the form that can receive focus to illustrate validation being overridden.
User input into a Windows Forms can include potentially invalid, malformed, or malicious information. Always check that the values that a user enters conform to the requirements for your application before using the values.