How to disable to enter some letters (a,b,c,d...) in textbox? I want to can write just numbers and colon (:) in textbox. Thanks.
Printable View
How to disable to enter some letters (a,b,c,d...) in textbox? I want to can write just numbers and colon (:) in textbox. Thanks.
Maybe a regex match would be easiest for this.
You can use the Keydown Event:
65722 = Colon KeyCode:Private Sub Textbox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Textbox1.KeyDown
If (e.KeyData >= 48 And e.KeyData <= 57) Or e.KeyData = 65722 Then
MyBase.OnKeyDown(e)
Else
e.SuppressKeyPress = True
End If
End Sub
48-57 = 0 to 9 keys
Oh yeah, that was a smart idea ^.^
But are you sure that 65722 is colon?
In my list of Charcodes, colon is 44
And japanese colon is 12289
I just think that 65722 seems so far away :P
That is the e.keydata value. I wrote a little app that has a textbox and 3 labels - one each for keycode, keydata and keyvalue. That way I can easily get the values for each, so that should be right.
It doesn't work :'(
I can enter numbers but can't colon ( : )
I tried with 58, but it's not.
Any help?
Check the link in my signature on textbox restrictions.
Bear in mind that the keydown method won't trap if anyone pastes text into the textbox so you'll need to add extra validation before you use the contents if you are just relying on the keydown approach.
Code:Private Sub TextBox1_TextChanged(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles TextBox1.TextChanged
For Each ch As Char In TextBox1.Text
If Not Char.IsDigit(ch) Then
If Not ch = ":" Then
'bad character
End If
End If
Next
End Sub
This is generally a bad approach. You don't need to filter user's input you need to validate it after the user is confirmed it by either clicking some button or pressing the Enter key.
Validating as entering can be OK, but a lot of the time it isn't. I have been wondering if hepeci is working with time values?
I just used dkahn's code in post #3 and found it very useful. I modified it like this
That way the numberpad digits 0 to 9 are included as well as backspace, mousewheel, and the others mentioned above in the comments. Colon isn't included here.Code:' 0 to 9 Backspace 0 to 9 on numberpad mousewheel up, down, PageUp, PageDown, End, Home, left, right, up and down arrows.
If (e.KeyData >= 48 And e.KeyData <= 57) Or e.KeyData = 8 Or (e.KeyData >= 96 And e.KeyData <= 105) Or (e.KeyData >= 33 And e.KeyData <= 40) Or e.KeyData = 46 Then
MyBase.OnKeyDown(e) ' e.KeyData = 46 for Delete
Else
e.SuppressKeyPress = True
End If
I also used dbasnett's code in case someone decides to paste into the combobox(not textbox for my situation) in question.