Simple textfield validating in Visual basic 2010

Simple way how to validate text fields.
If you have text field and you are using "_textChanged do something", then you probably know that it could be not enough. Depending on different specifications (usually such input is for numbers) and writing bad data like characters where should be numbers, it can make errors.
From my little experience, VB and similar program code is working based on "on error do something else".
In the following example I`m doing two things.
In the first I`m validating each keypress allowing just numbers, comma and decimal seperator,

Private Sub step1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles step1.KeyPress
        If (Not Char.IsNumber(e.KeyChar) AndAlso Not ".,-".Contains(e.KeyChar) AndAlso Not e.KeyChar = Microsoft.VisualBasic.Chr(Keys.Back)) Then
            e.Handled = True
        End If
    End Sub

And in the second - catching empty-string error. If someone deletes all content in the textbox, text is changed and passed string is empty, which does no good.

    Private Sub step1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles step1.TextChanged
        On Error GoTo 11
        If Not (step1.Text = String.Empty) Then
            parametrs.setStep() 'this pass error
        End If
    End Sub

Nav komentāru:

Ierakstīt komentāru