Greetings,
How can I prevent the user to enter characters but only numbers and '.' in a textbox in vb.net 2005?
thx...
Greetings,
How can I prevent the user to enter characters but only numbers and '.' in a textbox in vb.net 2005?
thx...
You could use the KeyDown event to check if the value of the key pressed is numeric or '.' and set the event property handled to true whenever the input is numeric or '.'. (I might be wrong with the value of the handled property since i don't remember if it was true or false that discarded the event and hindered the key to be input into the textbox)
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.
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.
Look at the ErrorProvider. Using that you can prevent focus from leaving control until correct value is entered, at the same time allowing user to press cancel or dialog close buttons.