Results 1 to 4 of 4

Thread: Trapping Non Numeric Key

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2002
    Location
    Pilipinas
    Posts
    441

    Trapping Non Numeric Key

    Im trying to trap non numeric key in TextBox but why this code don't Work?
    Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    If e.KeyChar < Chr(48) And e.KeyChar > Chr(57) Or e.KeyChar <> Chr(8) Then
    e.Handled = True
    End If
    End Sub

  2. #2
    Registered User
    Join Date
    Nov 2002
    Location
    Växjö, Sweden
    Posts
    314
    Try this....

    If Char.IsNumber(e.KeyChar) Then

    or

    If Not (Char.IsNumber(e.KeyChar)) AndAlso Strings.Asc(e.KeyChar) <> 8 Then

    if it was the other way around......
    Last edited by Athley; Dec 23rd, 2002 at 01:31 PM.

  3. #3
    Frenzied Member
    Join Date
    Oct 2002
    Location
    Gammapolis
    Posts
    1,474
    If you want to respond only to numerics and back space then your code must be something like this if you want to keep your won format:
    you should change the first AND with OR and the OR with AND


    If (e.KeyChar < Chr(48) Or e.KeyChar > Chr(57)) And (e.KeyChar <> Chr(8)) Then

  4. #4
    l33t! MrPolite's Avatar
    Join Date
    Sep 2001
    Posts
    4,428
    sorry if I'm reposting anything
    this works well for me:

    VB Code:
    1. Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    2.         Dim KeyASCII As Integer = Asc(e.KeyChar)
    3.         Dim BACK_SPACE As Integer = 8
    4.  
    5.         If KeyASCII <> BACK_SPACE AndAlso _
    6.            KeyASCII < 48 OrElse KeyASCII > 57 Then
    7.             ' Cancel the entered key, not a valid key
    8.             e.Handled = True
    9.         End If
    10.     End Sub


    btw I made my own textbox that accepts numbers only muhuhuhahahaha
    rate my posts if they help ya!
    Extract thumbnail without reading the whole image file: (C# - VB)
    Apply texture to bitmaps: (C# - VB)
    Extended console library: (VB)
    Save JPEG with a certain quality (image compression): (C# - VB )
    VB.NET to C# conversion tips!!

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