CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jan 2001
    Location
    Canada
    Posts
    150

    textbox Keypress

    How do I force a textbox to only accept numbers as a input and not text?

    Thankz, Drew
    [email protected]?SUBJECT=I Love Your Stuff
    Thanks, Drew

  2. #2
    Join Date
    Jun 2001
    Location
    MO, USA
    Posts
    2,868

    Re: textbox Keypress


    private Sub Text1_KeyPress(KeyAscii as Integer)
    If KeyAscii < 47 Or KeyAscii > 57 then
    KeyAscii = 0
    End If
    End Sub





  3. #3
    Join Date
    Sep 2001
    Location
    Montreal Canada
    Posts
    1,080

    Re: textbox Keypress

    Well the other suggestion works but if you want to block all key except numbers and Backspace here is the code

    ' ***************************************************************
    ' * *
    ' * Sub-routine name : *
    ' * TxtFTE_Keydown *
    ' * *
    ' * Objective : *
    ' * Checks which key was pressed *
    ' * *
    ' * Parameters : *
    ' * Keycode : The key that was pressed *
    ' * ****: Check wether shift was pressed*
    ' * or not. *
    ' * *
    ' ***************************************************************
    private Sub txtFTE_KeyDown(KeyCode as Integer, Shift as Integer)
    KeyCode = ValidateKeyNumbers(KeyCode)
    End Sub

    ' ***************************************************************
    ' * *
    ' * Sub-routine name : *
    ' * ValidateKeyNumbers *
    ' * *
    ' * Objective : *
    ' * Blocks all key except backspace and *
    ' * numbers *
    ' * *
    ' * Parameters : *
    ' * Keycode : The key that was pressed *
    ' * *
    ' ***************************************************************
    private Function ValidateKeyNumbers(byval KeyCode as Integer) as Integer
    If (KeyCode >= vbKey0 And KeyCode <= vbKey9) Or KeyCode = vbKeyBack Or _
    (KeyCode >= vbKeyNumpad0 And KeyCode <= vbKeyNumpad9) Or _
    (KeyCode = vbKeyDecimal) or 190 then ' 190 is the dot key
    ValidateKeyNumbers = KeyCode
    else
    ValidateKeyNumbers = 0
    End If
    End Function




    Nicolas Bohemier

  4. #4
    Join Date
    Jun 2000
    Posts
    41

    Re: textbox Keypress

    You could also try this. Mind you that this doesn't include the "." key, but it is fairly small and works.
    private Sub Text1_KeyPress(KeyAscii as Integer)
    If Not IsNumeric(Chr(KeyAscii)) then KeyAscii = 0
    End Sub





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