Validating event override

brainleak

Well-known member
Joined
Dec 20, 2016
Messages
54
Location
Barcelona area
Programming Experience
3-5
If I click on the x box at the upper right corner of the form to close it, a textbox validating event fires because of missing or wrong data. How can I avoid that?
 
You can't really do so without using unmanaged code if the user is going to use that Close button. Users should not be using that button and you should not encourage it. A properly-designed dialogue has OK and Cancel buttons and the user should be clicking one of them to close it. You can then set the CausesValidation property of the Cancel Button to False and clicking it will not raise any Validating events.
 
You can set e.Cancel to False in FormClosing event to allow form to close.

The form/container AutoValidate property can also be set to EnableAllowFocusChange to "get out" of a not validated control, this is often useful in combination with ErrorProvider component to give visual indication of not valid controls. Here you must use explicit validation since user is not locked to a control until valid data is given.

More about validation and both the above here: User Input Validation in Windows Forms | Microsoft Docs
 
In this example I'm using a textbox and a cancel button and it does work as the form closes when I click cancel. However even in this case the messagebox displays its warning before the form is closed. How can I prevent it?
Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        btnClose.CausesValidation = False
    End Sub

    Private Sub TextBox1_Validating(sender As Object, e As CancelEventArgs) Handles TextBox1.Validating
        If TextBox1.Text = "" Then
            MsgBox("Don't leave it blank")
        End If
    End Sub


    Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
        Me.Close()
    End Sub

End Class
 
Last edited by a moderator:
Back
Top