Friday, June 30, 2006

Using correct textbox event handler

You should come across scenario where you need to validate value of a textbox and then do some calculation after someone enter value into a textbox and leave the field. Typically we will just LostFocus event and perform the two tasks in this event handler block.

In .net, you should split your code to Validating and Validated events. The following code is a sample.
    
Private Sub txtCubicCapacity_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtCubicCapacity.Validating
        If txtCubicCapacity.Text.Length > 0 Then
            If Not ValidateCubicCapacity(txtCubicCapacity.Text) Then
                e.Cancel = True
            End If
        End If
    End Sub

    Private Sub txtCubicCapacity_Validated(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtCubicCapacity.Validated
        If txtCubicCapacity.Text.Length > 0 Then
            txtVehicleClass.Text = GetVehicleClassByCubicCapacity(txtCubicCapacity.Text)
        End If
    End Sub

    Public Function ValidateCubicCapacity(ByVal CubicCapacity As String) As Boolean
        ValidateCubicCapacity = False

        If Not IsNumeric(CubicCapacity) Then
            MsgBox("Cubic Capacity must be in numeric.", MsgBoxStyle.Exclamation, "Validation")
            Exit Function
        End If

        If Not Convert.ToInt32(CubicCapacity) > 0 Then
            MsgBox("Cubic Capacity must be more than 0.", MsgBoxStyle.Exclamation, "Validation")
            Exit Function
        End If

        ValidateCubicCapacity = True
End Function
The reason why you should use Validating event to do validation code is because this event expose e.Cancel property within the event handler so that if validation fails, you just need to set this property to false and exit the block. The textbox will acknowledge the validation failure and set focus back to textbox.

The reason that calculation code should be in Validated event instead of LostFocus is that Validated event is the event raised immediately after validated. This ensures that your code is executed only after proper validation is successfully done.

No comments: