Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow user to enter only numbers in a textbox in vb.net?

Tags:

vb.net

How can I prevent the user to enter characters but only numbers and '.' in a textbox in vb.net 2005?

like image 849
Davideg Avatar asked Dec 04 '22 11:12

Davideg


2 Answers

The following will allow you to test for specific key values (from http://www.daniweb.com/forums/thread127299.html):

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    If (Microsoft.VisualBasic.Asc(e.KeyChar) < 48) _
              Or (Microsoft.VisualBasic.Asc(e.KeyChar) > 57) Then
            e.Handled = True
    End If
    If (Microsoft.VisualBasic.Asc(e.KeyChar) = 8) Then
            e.Handled = False
    End If
End Sub

If this isn't what you are looking for, try the isNumeric() function.

like image 127
Edward Leno Avatar answered Mar 06 '23 08:03

Edward Leno


Just to help, I had a snippet which I was making for a calculator which may help, it allows Delete, Backspace, Digits and the '.' char. You can also add in a call to a function to process the text box on the pressing of the Enter key.

  Private Sub Box_Input_KeyDown(ByVal sender As Object, _
                                ByVal e As System.Windows.Forms.KeyEventArgs) _
                                Handles Box_Input.KeyDown



    If Char.IsDigit(Chr(e.KeyValue)) Or _
       Chr(e.KeyValue) = "¾"c Or _
       e.KeyData = Keys.Delete Or _
       e.KeyData = Keys.Back Then

        If Chr(e.KeyValue) = "¾"c Then
            If Box_Input.Text.Contains(".") Then
                e.SuppressKeyPress = True
            Else
                e.SuppressKeyPress = False
            End If
        End If
    ElseIf e.KeyData = Keys.Enter Then
         `State a call to function for when Enter is pressed`
    Else
        e.SuppressKeyPress = True
    End If

End Sub

This code allows entry of all numbers, the back space and delete keys as well as only allowing one '.' in the text. An idea might be to add the TAB function to allow Tab stops.

like image 34
Tom 'Blue' Piddock Avatar answered Mar 06 '23 07:03

Tom 'Blue' Piddock