Simple Problem: Allow Only Number Input In Text Box
Hi all,
I've got a simple problem / request. How do I allow only numbers to be inputted into a text box ?
I've been reading up and people suggest Keypress but that Method is available for the textbox from the code window drop down.
Any ideas ?
[270 byte] By [
Donaghy] at [2007-12-26]
Either use masked textbox with a mask, or NumericUpDown, or if you want to stay with textbox, add a keypressed handler with this code
if e.KeyCode < '0' Or e.KeyCode > '9' Then
e.Handled = True
End If
--
SvenC
chek the keycode if it is 46 then allows it.
add on the top of to the any of the above code.
if not (texbox1.text.indexof(".") > 0) then
if e.keycode = 46 then exit sub
end if
Hi!
There is how I do.
You can add case if "ENTER" key is pressed for automation.
CODE:
Private Sub yourTextBox_KeyPress(ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.KeyPressEventArgs) _
Handles yourTextBox.KeyPress
'set flag that in input box aren't commas
Dim isComma = False
Dim charArray() As Char = yourTextBox.Text.ToCharArray()
'set flag if in input box is comma
For Each c As Char In charArray
If c = "." Then
isComma = True
End If
Next
'now checks key pressed for digits, comma (only one) and backspace
'char is not diplayed if other key are pressed
If e.KeyChar < "0" Or e.KeyChar > "9" Then
If Not e.KeyChar = "." Or isComma Then
If Not e.KeyChar = vbBack Then
e.Handled = True
End If
End If
End If
End Sub