none
Avoi past on text box

    Question

  • Hi all

    1) i would like to avoid to copy a alfanumeric value from a TextBox and paste it in

    a TextBox that should accept just numbers ( checked with keypress event)

    But i dont want to disable Shortcuts  for the Numeric TextBox

    2) And if i want the numeric TextBox accepting  paste of numbers ??

    Any Idea ?

    Bye Claudio

    Claudio

    Tuesday, November 28, 2017 7:10 PM

Answers

All replies

  • The following is a base that is open to change. WinProc prevents anything but numbers from being entered via the Windows Clipboard.

    Imports System.ComponentModel
    Public Class numericTextbox
        Inherits TextBox
    
        <Category("Behavior")>
        <Description("Acceptable min value")>
        Public Property Min As Integer
    
        <Category("Behavior")>
        <Description("Acceptable max value")>
        Public Property Max As Integer
    
    
        <Browsable(False)>
        Public ReadOnly Property IsValid As Boolean
            Get
                Return IntegerValue.Between(Min, Max) AndAlso DoubleValue.Between(Min, Max)
            End Get
        End Property
    
        Const WM_PASTE As Integer = &H302
    
        <Browsable(False)>
        Public ReadOnly Property DoubleValue As Double
            Get
                If String.IsNullOrWhiteSpace(Text) Then
                    Return 0
                Else
                    Return CDbl(Text)
                End If
            End Get
        End Property
        <Browsable(False)>
        Public ReadOnly Property IntegerValue As Integer
            Get
                If String.IsNullOrWhiteSpace(Text) Then
                    Return 0
                Else
                    Return CInt(Text)
                End If
            End Get
        End Property
        Protected Overrides Sub OnKeyPress(ByVal e As System.Windows.Forms.KeyPressEventArgs)
            Dim Value As String = Text
            Value = Value.Remove(SelectionStart, SelectionLength)
            Value = Value.Insert(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 Text.Contains(".") Or e.KeyChar = "."c And
                      SelectedText.Contains(".")) OrElse (e.KeyChar = "-"c And
                                                             SelectionStart = 0))
    
            MyBase.OnKeyPress(e)
        End Sub
        Protected Overrides Sub WndProc(ByRef m As Message)
            If m.Msg = WM_PASTE Then
                Dim Value As String = Text
                Value = Value.Remove(SelectionStart, SelectionLength)
                Value = Value.Insert(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
    Public Module GenericExtensions
        <Runtime.CompilerServices.Extension>
        Public Function Between(Of T As IComparable(Of T))(ByVal actual As T, ByVal lower As T, ByVal upper As T) As Boolean
            Return actual.CompareTo(lower) >= 0 AndAlso actual.CompareTo(upper) < 0
        End Function
    End Module


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Tuesday, November 28, 2017 7:27 PM
    Moderator
  • If it is for OS >= Vista, you can just use the ES_NUMBER style.
    Tuesday, November 28, 2017 7:45 PM
  • 1) i would like to avoid to copy a alfanumeric value from a TextBox and paste it in

    a TextBox that should accept just numbers ( checked with keypress event)

    But i dont want to disable Shortcuts  for the Numeric TextBox

    2) And if i want the numeric TextBox accepting  paste of numbers ??

    What should happen if the user tries to paste something other than a number?
    1. Only the numeric characters of the pasted text should be inserted. This may produce odd results for numbers like '1.5e2', but would be OK if only integers were being pasted.
    2. The paste operation should be ignored.

    Tuesday, November 28, 2017 7:54 PM
  • For Each car As Char in Textbox1.Text  'alphanumeric
        If Char.IsDigit(car) Then
            Textbox2.Text &= car    'concatenate only digits
        End If
    Next car
     

    Solitaire

    Wednesday, November 29, 2017 2:40 AM
  • Hi Karen 

    thanks for the solution, but it is too complicated for the level i am now.

    I will keep id and try to use it as soon as i understand what ti does.

    By the way, can you suggest me a book that explain not just the base of visual basic. I meen ad advanced book 

    Have a good day and thank you again.

    Claudio

    Wednesday, November 29, 2017 11:07 AM
  • I will keep id and try to use it as soon as i understand what ti does.

    It is possible to do what you want with some very simple coding but you have to specify the task more clearly.  Are you trying to paste floating point numbers or integers only?  Do you want to simply ignore any character that is not numeric, or do you want to completely reject anything that is not a proper,valid number?  Remember that 'numbers' can be text like "1", "$3,712.21", "-35.5", "1.5e2" and many other variations, so you need to know what you would accept and what you would not.  Should there be an indication to the user if there is a problem, or is it sufficient to just process or ignore?  Even though it seems a simple task it still needs a careful description, but once you have a good description the code should be easy.

    Wednesday, November 29, 2017 11:17 AM
  •  it is too complicated for the level i am now.

    use es_number as suggested above if you don't target xp, it is 5 lines of code
    Wednesday, November 29, 2017 11:18 AM
  • Why not just use the MaskedTextBox control and set the Mask property to numeric? (e.g. "0000000")

    Paul ~~~~ Microsoft MVP (Visual Basic)

    Wednesday, November 29, 2017 3:25 PM
  • Hi all

    you are rigth, i must be clear

    I'm using Visual Basic and WIN FORMS and developing a business application

    So in the all the  forms I have 2 type of textboxs. Let's call them A and B

    A : can accept all printable char

    B : can contain just number (integer or decimal)

    So, what i wish with the Copy and Paste (mouse rigth ckick) is :

    A to A  - yes

    B to A - yes

    B to B - yes

    A to B  - ONLY if A contains only digits

    Claudio

    Wednesday, November 29, 2017 7:24 PM
  • I'm using Visual Basic and WIN FORMS and developing a business application

    That description is still inconsistent.   You say "B : can contain just number (integer or decimal)" but your question only refers to pasting, not to keyboard entry.  Do you also want to prevent the user from entering a nonnumeric value into the text box by typing at the keyboard?   The difference is important.  If the text box can only be a number then all non-numeric entry can be prevented.   If it is only pasting a non numeric number that you want to prevent, then the paste operation has to be distinguished from keyboard entry, and that is more complicated.

    You also haven't indicated what should happen when the user attempts to paste a non-numeric value.   Should the result simply be ignored, or should there be a message?  Should the code attempt to convert the input to a number, or just reject it?

    You can start with the simplest case - only valid numbers can be entered or pasted, but the application will attempt to convert an entry that contains non-numeric characters into a valid number.  It will tell the user if the attempt fails, and will not insert anything.  This will be done when the user finishes typing or pasting and tries to move onto the next control.  The text box cannot be left blank.

        Private Sub TextBoxB_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles TextBoxB.Validating
            Dim D As Double
            If Double.TryParse(TextBoxB.Text, D) Then
                TextBoxB.Text = D.ToString
            Else
                MsgBox("Invalid Numeric Value")
                TextBoxB.Text = ""
                e.Cancel = True
            End If
        End Sub
    If you want to force numeric entry only for pasting then that can be done through a custom control.  If you want to warn the user about a non-numeric entry while they are still typing, then you can add code similar to that above in the keypress event of the control, to catch each keypress as it happens, not just when they finish and move on.  That is not relevant to pasting, of course.

    • Edited by AcamarMVP Wednesday, November 29, 2017 8:35 PM sp
    Wednesday, November 29, 2017 8:32 PM
  •  Just as another small example of creating your own TextBox control class,  you can add the MyTextBox class in your code as shown below.  Then Build or Run your application.  After that you will see the MyTextBox control at the top of your toolbox.  You can replace your numeric only textboxes with the MyTextBox control.

     Test it in a new form project if you want.  8)

    Public Class Form1 'your form code... End Class Public Class MyTextBox Inherits TextBox Private Const WM_PASTE As Integer = &H302

    'add the characters you consider valid in this string Private LegalChars As String = "1234567890." & Chr(3) & Chr(22) Protected Overrides Sub OnKeyPress(e As KeyPressEventArgs) If Not LegalChars.Contains(e.KeyChar) AndAlso e.KeyChar <> vbBack Then MessageBox.Show(e.KeyChar & " is Not a number.") e.Handled = True End If MyBase.OnKeyPress(e) End Sub Protected Overrides Sub WndProc(ByRef m As Message) If m.Msg = WM_PASTE Then For Each c As Char In Clipboard.GetText If Not LegalChars.Contains(c) Then MessageBox.Show("Clipboard does not contain a valid number.") Return End If Next End If MyBase.WndProc(m) End Sub End Class



    If you say it can`t be done then i`ll try it

    • Edited by IronRazerz Wednesday, November 29, 2017 9:23 PM
    Wednesday, November 29, 2017 8:56 PM
  • ok,

    the A > B A to B  - ONLY if A contains only digits regards just Paste

    I already control keyPress evemt  for textbox  to avoid Literal to be inserted in the Numeric textBox.

    No msg to the user if he try to Paste Literal - i mean no action.

    Thursday, November 30, 2017 6:22 AM
  • Here on our website one which does the same as from Karen and Ray, 

    (Prevent typing in non numbers and also prevent pasted non numerics)

    The past part is however based on the fact that somehow the textbox has to be leaved to process it. 

    http://www.vb-tips.com/WindowsFormsNumericTextBox.ASPX


    Success
    Cor

    • Marked as answer by Claudio111 Friday, December 08, 2017 6:30 AM
    Thursday, November 30, 2017 8:10 AM
  •  Have any of the answers or suggestions given to you here answered your question.  If so,  then please remember to mark the post or posts that answered your question as the answer(s).  If you are having problems implementing the examples or suggestions,  then let us know which one(s) you have tried and what is not working.


    If you say it can`t be done then i`ll try it

    Friday, December 08, 2017 12:33 AM