Results 1 to 3 of 3

Thread: Preventing pastes in textboxes

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Mar 2000
    Location
    Montreal, QC
    Posts
    24

    Question

    Hello all,

    Could anyone help me with my problem? What I need to do is make a textbox which can only contain numbers, not letters. Using the Keypress event, I can already make sure they can't type in letters, but unfortunately, there's nothing to stop users from just pasting it in. I can also disable the little the popup menu on the textbox, but the CTRL-V and SHIFT-INS keys still work. Is there a way to disable pastes on a textbox?

    Thanks in advance,
    JMik

  2. #2
    Hyperactive Member
    Join Date
    Mar 2000
    Posts
    461
    Try this :

    (Note: I haven't implemented this, just off the top of my head)

    Code:
    Public bCheckInput as Boolean
    Public sOldValue as String
    
    Private Sub TextBox_KeyPress(KeyAscii As Integer)
      If ( KeyAscii < Asc("0") Or KeyAscii > Asc("9")) And KeyAscii <> 8 Then
        KeyAscii = 0
      End If
    
      sOldValue = TextBox.Text
      bCheckInput = False
    End Sub
    
    Private Sub TextBox_Change()
      If bCheckInput Then
        If Str(Val(TextBox.Text)) <> TextBox.Text Then
          TextBox.Text = sOldValue
        End If
      End If
    
      bCheckInput = True
    End Sub
    What this does is the following :

    1. If you press a key then it will test the key and make sure it is between the number 0 and the number 9 (OR it is the backspace key).

    2. When a key is pressed it will set the boolean to False meaning "Do not Check this value in the Change Event"

    3. When the value of the text box has changed run the TextBox_Change subroutine. (Note this also occurs when you do a keypress providing it isn't set to 0 which means no key was pressed)

    4. If the key was pressed because the KeyPress worked (ie a number) then as the bCheckInput is false it does nothing and then sets bCheckInput to TRUE.

    5. If bCheckInput is TRUE (Either because it has done a check or a paste occured) Then check to see that converting the string to a number and BACK to a string is the exact same number as what it was without being converted to a number (ie ONLY numbers entered). If it has then revert it to what it was before you changed it.

    Hope that works for you.

  3. #3

    Thread Starter
    Junior Member
    Join Date
    Mar 2000
    Location
    Montreal, QC
    Posts
    24

    Thumbs up

    Quite ingenious Gen-X, I never would have thought of it. It works great, thanks so much...

    JMik

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