I'm trying to restrict the input of a text box to allow only numbers (0-9). I intercept "KeyDown" and update Textbox1.Text only if a number is typed:
(Updated)
----------
----------Code:Public Class Form1 Dim strPreviousID As String = "" Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles Textbox1.KeyDown If e.KeyValue > 95 And e.KeyValue < 106 Then ' Only ASCII values from "0" to "9". strPreviousID += Chr(e.KeyValue - 48) ' ASCII value is Keyboard - 48 Else TextBox1.Text = strPreviousID End If strPreviousID = TextBox1.Text End Sub End Class
PROBLEM (Updated): If the very first character is not a number, it STILL appears in the text box. If you type anything other than a number, the box contents are replaced with that one letter.
For the life of me, I can not figure out how to stop non-numeric values from appearing.
All "solutions" found online either don't work with VB.Net or are wildly unnecessarily complex.
So instead of "KeyDown", I tried "TextChanged":
This comes with its own set of problem. Numbers work fine, but "If" line throws an exception if anything other than a number is typed.Code:Public Class Form1 Dim strPreviousID As String = "" Private Sub Textbox1_TextChanged(sender As Object, e As EventArgs) Handles Textbox1.TextChanged If Textbox1.Text.Last.ToString >= "0" And Textbox1.Text.Last.ToString <= "9" Then ' Only "0" thru "9". strPreviousID += Textbox1.Text.Last.ToString Else Textbox1.Text = strPreviousID End If Textbox1.Text = strPreviousID End Sub End Class
I'm stumped. TIA




Reply With Quote
