dcsimg
Results 1 to 15 of 15

Thread: Textbox numeric type and paste only

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Jun 2014
    Posts
    353

    Textbox numeric type and paste only

    I tried to use a maskedtextbox but it created more issues for this particular use I have. For other text forms I use maskedtextbox but for this one instance I cannot.

    Anyways, the textbox is set to 6 characters limit and I want it to only allow input and pasting of numbers.

    I am able to restrict input but not able to control what is pasted:

    Code:
        Private Sub txtStoreID_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtStoreID.KeyPress
            If (Microsoft.VisualBasic.Asc(e.KeyChar) < 48) Or (Microsoft.VisualBasic.Asc(e.KeyChar) > 57) Then
                e.Handled = True
            End If
            If (Microsoft.VisualBasic.Asc(e.KeyChar) = 8) Then
                e.Handled = False
            End If
            If Keys.Control AndAlso Keys.V Then
                e.Handled = False
            End If
        End Sub
    I understand that:
    97 - 122 = Ascii codes for simple letters
    65 - 90 = Ascii codes for capital letters
    48 - 57 = Ascii codes for numbers

    I only want Ctrl+C, CTRL+V, Enter and Backspace to work.

    I also want to limit pasting, because at this moment typing letters is blocked but pasting letters still happens.

  2. #2
    I don't do your homework! opus's Avatar
    Join Date
    Jun 2000
    Location
    Good Old Europe
    Posts
    3,863

    Re: Textbox numeric type and paste only

    I do use the .TextChanged for that:
    Code:
    Private Sub YourTextBox_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles YourTextBox.TextChanged
            Dim ThisTextBox As TextBox = DirectCast(sender, TextBox)
            Dim CheckString As String = "1234567890"  'A String containing the allowed Chars.
            Dim theText As String = ThisTextBox.Text
            Dim Letter As String
            Dim SelectionIndex As Integer = ThisTextBox.SelectionStart
            Dim Change As Integer
            For x As Integer = 0 To ThisTextBox.Text.Length - 1
                Letter = ThisTextBox.Text.Substring(x, 1)
                If CheckString.Contains(Letter) = False Then
                    theText = theText.Replace(Letter, String.Empty)
                    Change = 1
                End If
            Next
            ThisTextBox.Text = theText
            ThisTextBox.Select(SelectionIndex - Change, 0)
        End Sub
    You're welcome to rate this post!
    If your problem is solved, please use the Mark thread as resolved button


    Wait, I'm too old to hurry!

  3. #3

    Thread Starter
    Hyperactive Member
    Join Date
    Jun 2014
    Posts
    353

    Re: Textbox numeric type and paste only

    Thanks for that, I'm having a little bit of trouble understanding what the code is doing trying to study it.

    What's happening now with the above code is that it's erasing the content of the textbox entirely if there are letters being pasted. Pasting numbers is fine. I was hoping to detect letters in the paste and not make any change to the textbox then rather than deleting the contents.

  4. #4
    PowerPoster
    Join Date
    Oct 2008
    Location
    Midwest Region, United States
    Posts
    3,569

    Re: Textbox numeric type and paste only

    Then you'd need to store the value of it before any attempt to change it is made and "roll it back" if the change contains letters.

  5. #5
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,522

    Re: Textbox numeric type and paste only

    Hello,
    Here is a custom TextBox that checks for data pasted from the Windows Clipboard and disallows non-numeric values via Decimal.TryParse.
    Code:
    Public Class numericTextbox
       Inherits TextBox
    
       Const WM_PASTE As Integer = &H302
    
       Protected Overrides Sub OnKeyPress(ByVal e As System.Windows.Forms.KeyPressEventArgs)
          Dim Value As String = Me.Text
          Value = Value.Remove(Me.SelectionStart, Me.SelectionLength)
          Value = Value.Insert(Me.SelectionStart, e.KeyChar)
          e.Handled = CBool(Value.LastIndexOf("-") > 0) _
             Or Not (Char.IsControl(e.KeyChar) OrElse _
             Char.IsDigit(e.KeyChar) OrElse _
             (e.KeyChar = "."c And Not Me.Text.Contains(".") Or _
             e.KeyChar = "."c And _
             Me.SelectedText.Contains(".")) OrElse (e.KeyChar = "-"c And Me.SelectionStart = 0))
          MyBase.OnKeyPress(e)
       End Sub
    
       Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
          If m.Msg = WM_PASTE Then
             Dim Value As String = Me.Text
             Value = Value.Remove(Me.SelectionStart, Me.SelectionLength)
             Value = Value.Insert(Me.SelectionStart, Clipboard.GetText)
             Dim result As Decimal = 0
             If Not Decimal.TryParse(Value, result) Then
                Return
             End If
          End If
          MyBase.WndProc(m)
       End Sub
    
    End Class

  6. #6
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    34,889

    Re: Textbox numeric type and paste only

    If it is only numbers, would a NumericUpDown control suffice?
    My usual boring signature: Nothing

  7. #7

    Thread Starter
    Hyperactive Member
    Join Date
    Jun 2014
    Posts
    353

    Re: Textbox numeric type and paste only

    Pardon my ignorance kevininstructor, how would I use that?

  8. #8
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,522

    Re: Textbox numeric type and paste only

    Quote Originally Posted by a_ahmed View Post
    Pardon my ignorance kevininstructor, how would I use that?
    Create a new class file in your project name it numericTextbox.vb, replace the default contents with the code I replied with. Now re-build the project, display the form you want to use it in, select the toolbox and you will find the TextBox at the top of the toolbox. Add it to the form. Run the project, try and paste a-z characters into the TextBox.

  9. #9

    Thread Starter
    Hyperactive Member
    Join Date
    Jun 2014
    Posts
    353

    Re: Textbox numeric type and paste only

    Brilliant solution, it appears to work mighty fine! Thank you.

  10. #10

    Thread Starter
    Hyperactive Member
    Join Date
    Jun 2014
    Posts
    353

    Re: Textbox numeric type and paste only

    The only thing I needed to change or it failed to build was

    Me.txtStoreID = New Global.MainForm.numericTextbox()

    It needed to set it to global

    It keeps changing back and forth in the form code and asking me to change to global each time i try to build

  11. #11
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,522

    Re: Textbox numeric type and paste only

    Download this solution, note I placed the TextBox into a class project so you can use it in any project.

  12. #12
    Registered User
    Join Date
    Feb 2020
    Posts
    1

    Smile Re: Textbox numeric type and paste only

    Quote Originally Posted by kareninstructor View Post
    Download this solution, note I placed the TextBox into a class project so you can use it in any project.
    Dear Karen,

    I am new to VB.net. I want to refer to your example to understand how CLASS works, but the link is no longer valid. Could you share the file for me again? Thank you very much.

  13. #13
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,522

    Re: Textbox numeric type and paste only

    Quote Originally Posted by aeromika View Post
    Dear Karen,

    I am newbie on VB.net. I want to refer to your example to understand how CLASS works, but the link is no longer valid. Could you share the file again? Thank you very much.
    There is no need for the file as the code is presented above. Simply create a new class with the name numericTextbox.vb, copy paste the code from above, compile the project then when a form is shown in the IDE the TextBox will appear at the top of the toolbox, double click to add it to the form like any other control.

  14. #14
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    23,119

    Re: Textbox numeric type and paste only

    @Karen... Looks familiar. I remember that from somewhere. Shouldn't you impose the maxlength when keypressing or pasting?

  15. #15
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,522

    Re: Textbox numeric type and paste only

    @.paul., seems the developer should set the MaxLength which the paste code respects by way of MaxLength property. Yet you bring up a point many may not consider to set MaxLength and perhaps range checking.

Posting Permissions

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



Featured


Click Here to Expand Forum to Full Width