TextBox Validation in VB.NET and Windows Forms

17,757

Solution 1

There is a much easier way to validate this. Try convert the text in the edit box to a floating point number. If you catch an exception, the number is not valid.

Trying to validate keystroke by keystroke is going to cause you many headaches.

Solution 2

An even better way is to use a control that supports decimals (if that is you're using something like infragistics, componentone, devexpress, etc.) The user gets visual cues and can do neat things like click the arrows to advance the numbers.

If you're using plain old winforms, have a look at the masked edit control.

Personally I find it HUGELY irritating when applications try to correct me and i'm not done entering data. It's much more user friendly to let the user finish and then notify them if there are any problems.

Solution 3

txtMobil.Text = Format(txtMobil.Text, "###-###-####")
Share:
17,757
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I'm using the following code to validate the text entered by user. It works perfectly fine. But I want to add the backspace feature so as to allow the user to delete the wrongly entered number.

    I have tried a couple of things and they worked but before last digit (after the decimal point) i.e. it does not allows to delete after the number has been completely entered. number is being entered in the format: 12313213.45

    What shall I do?

    Private Sub TextBox5_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox5.KeyPress
    
        'validation '
        Dim KeyAscii As Short = Asc(e.KeyChar)
        If Not ((KeyAscii >= System.Windows.Forms.Keys.D0 And KeyAscii <= System.Windows.Forms.Keys.D9) Or (KeyAscii = System.Windows.Forms.Keys.Back) Or Chr(KeyAscii) = "." Or (Chr(KeyAscii) Like "[ ]")) Then
            KeyAscii = 0
            TextBox5.Focus()
        End If
        If KeyAscii = 0 Then
            e.Handled = True
        End If
    
        If TextBox5.Text.IndexOf(".") >= 0 And e.KeyChar = "." Then
            e.Handled = True
        End If
    
        If TextBox5.Text.IndexOf(".") > 0 Then
            If TextBox5.SelectionStart > TextBox5.Text.IndexOf(".") Then
                If TextBox5.Text.Length - TextBox5.Text.IndexOf(".") = 3 Then
                    e.Handled = True
                End If
            End If
        End If
    End Sub