Click to See Complete Forum and Search --> : Allow Only Numeric


HerickPaiva
May 3rd, 2001, 02:54 PM
Hi,

How can I block a user from typing non-numeric characters (a,b,c,d...) in a textbox adn display a message??

Herick

slcotten
May 3rd, 2001, 03:13 PM
yes...

I use this code:


private Sub Text1_KeyPress(KeyAscii as Integer)
If InStr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", UCase$(Chr$(KeyAscii))) <> 0 then KeyAscii = 0: Beep
End Sub




You can add other characters such as "?\'/;:.>,<" to the "ABCD...." string if you want.

HerickPaiva
May 3rd, 2001, 03:17 PM
cool!!! But now, how do I clear the contents of the textbox after displaying a message???? I try "txtsearch.text = "" but that adds a space in the textbox...how do I clear it?

Raptors Fan
May 3rd, 2001, 03:27 PM
There are many ways of doing it but here is the way I like to do it and you don't need to provide a message.


private Sub Text1_KeyPress(KeyAscii as Integer)
Dim strValid as string

strValid = "1234567890"

' if it's not a control code
If KeyAscii > 26 then _
If InStr(strValid, Chr(KeyAscii)) = 0 then _
KeyAscii = 0
End Sub

slcotten
May 3rd, 2001, 03:50 PM
that should work... just make sure that you didn't write txtsearch.text = " ". That would put a space in the text box! :-)

HerickPaiva
May 3rd, 2001, 03:55 PM
If I type a "d" or any letter, I make a popup message to appear...after clicking ok , the letter is still there. here is the code:

If KeyAscii = 8 Then Exit Sub
If Not IsNumeric(Chr(KeyAscii)) Then
MsgBox "Please Enter only Alpha-Numeric Characters."
txtSearch.Text = ""
End If

I need to totally clear whatever they typed before.

Herick

slcotten
May 3rd, 2001, 04:03 PM
that is because the "d" is placed in txtsearch after your code executes... you must reset KeyAscii to zero in place of txtSearch.text = "" like so:

If KeyAscii = 8 Then Exit Sub
If Not IsNumeric(Chr(KeyAscii)) Then
MsgBox "Please Enter only Alpha-Numeric Characters."
KeyAscii = 0
End If

slcotten
May 3rd, 2001, 04:05 PM
actually I did not think of it but you can just add the KeyAscii = 0 statement... I was forgetting that your textbox could have more than the type chararter in it and you wanted to total clear it