# Restricting text entered into Text Box-VB.Net



## duner80 (Oct 1, 2003)

Currently, I have a textbox defined as an integer.
I would like to restrict the user input to be only a range of numbers between 0-100.
If it is above the range, I would like to have a message box appear saying "Input can only be between 0 and 100"
How do I go about this?


----------



## RGregory (Jul 27, 2005)

Put the following in the text box's keypress event...

const strChars = "0123456789" & vbback
dim x as Integer

If InStr(1, strChars, Chr(KeyAscii)) = 0 Then
Cancel = True
End If

If Int(<TextBoxName>.Text) > 100 then
MessageBox.Show("Number must be no greater than 100.")
x = len(<TextBoxName>.Text)
do until int(left(<TextBoxName>.Text, x)) <= 100
x -= 1
loop
<TextBoxName>.Text = left(<TextBoxName>.Text, x)


----------



## duner80 (Oct 1, 2003)

I inserted the code, but I have several errors. I am learning the language/program, and I am unfamilair with how to fix them still.
Attached is a screen print showing the errors. Any more help is appreciated.
Thanks,
JD


----------



## duner80 (Oct 1, 2003)

Ok, I played around with the code, and this is what I changed it too.

Const strChars = "0123456789" & vbBack
Dim LT1I, KeyAscii As Integer

If InStr(1, strChars, Chr(KeyAscii)) = 0 Then

End If

If Int(TextBox1.Text) > 100 Then
MessageBox.Show("Number must be no greater than 100.")
LT1I = Len(TextBox1.Text)
Do Until LT1I <= 100
LT1I -= 1
Loop
TextBox1.Text = LT1I
End If

Builds alright, but when I debug, it gives the following message at the line with red text above: A first chance exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll


----------



## RGregory (Jul 27, 2005)

Don't have .Net available to me at this time. I'll look up the code I have when I return to my house this evening. I believe it may be

If InStr(1, strChars, e.KeyPress) = 0 Then
e.Cancel = True
End If

and you may have to check the second If statement to take into account null values. I know in earlier versions you would have done the following

If Not IsNull(TextBox1.Text) Then
... second if statement ...
End If

I believe if you put this in the compiler will tell you what is needed.

Lastly, this needs to be in the TextBox1.Keypress event, not the TextChanged event.


----------

