I have a TextBox (txtSVID) which I want to accept only numeric input but without decimals (integers only).
In case the input is not an integer, I want the user to be notified, the TextBox to be emptied and the focus to remain on the TextBox until the input is an integer.
I use the following code:
Private Sub txtSVID_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtSVID.KeyPress
Dim flag As Boolean
Dim KeyAscii As Integer
KeyAscii = Asc(e.KeyChar)
If flag = False Then
' Set the flag to True to prevent re-entry of the code below.
flag = True
' Determine if the text of the control is a number.
Select Case KeyAscii
Case 48 To 57
'provide no handling for any other keys
KeyAscii = 0
MsgBox("You must enter a positive integer")
' Reset the flag so other TextChanged events are processed correctly.
flag = False
It does prompt the user each time he tries to enter an invalid character but the TextBox content is not cleared from the invalid characters and the user may leave the TextBox leaving invalid characters in the TextBox.
I would also appreciate if I could format the TextBox text with thousands separators.
Any help would be greatly appreciated.