How can I prevent the user to enter characters but only numbers and '.' in a textbox in vb.net 2005?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With