CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 8 of 8
  1. #1
    Join Date
    Mar 2001
    Posts
    38

    Allow Only Numeric

    Hi,

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

    Herick


  2. #2
    Join Date
    Apr 2001
    Posts
    95

    Re: Allow Only Numeric

    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.


  3. #3
    Join Date
    Mar 2001
    Posts
    38

    Re: Allow Only Numeric

    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?


  4. #4
    Join Date
    Apr 2001
    Location
    Canada
    Posts
    78

    Re: Allow Only Numeric

    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







  5. #5
    Join Date
    Apr 2001
    Posts
    95

    Re: Allow Only Numeric

    that should work... just make sure that you didn't write txtsearch.text = " ". That would put a space in the text box! :-)


  6. #6
    Join Date
    Mar 2001
    Posts
    38

    Re: Allow Only Numeric

    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


  7. #7
    Join Date
    Apr 2001
    Posts
    95

    Re: Allow Only Numeric

    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



  8. #8
    Join Date
    Apr 2001
    Posts
    95

    Re: Allow Only Numeric

    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


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured