How do I convert this KeyPressEvent so it can be called from multiple textboxes?

Cynolycus 260 Reputation points
2023-02-09T12:44:37.68+00:00

I'm trying to learn in my spare time and don't know if this is the best way of doing this, but it seems to work for a single textbox using the keypress event.

The idea was to ensure

  1. A negative symbol can only be placed at the start of the text
  2. All decimals, positive or negative were preceded with a 0
  3. Only one decimal point could exist in the text
  4. Only a decimal could start with a 0
  5. Allow the backspace to work
  6. Prevent all other keys from working
       Private Sub TxtLatShift_KeyPresssender(sender As Object, e As KeyPressEventArgs) Handles TxtLatShift.KeyPress
   
           Dim TargetChr As String
           Dim MyPos As String
   
           TargetChr = e.KeyChar
           MyPos = InStr(TxtLatShift.Text, TargetChr)
   
           Select Case TargetChr
   
               Case "-"
   
                   'Allow only one negative symbol
                   If TxtLatShift.Text.Length < 1 Then e.Handled = False Else e.Handled = True
   
               Case "."
   
                   'If no character is present this places a "0" before the decimal
                   If TxtLatShift.Text = "" Then           'Check if the textbox is empty
                       TxtLatShift.Text = "0"              'Insert a "0" if blank
                   ElseIf TxtLatShift.Text = "-" Then      'Check if the textbox contains a negative
                       TxtLatShift.Text = "-0"             'Insert a "-0" if no other number present
                   End If
   
                   'Check for existing decimal point and if found reject extras
                   If MyPos > 0 Then e.Handled = True Else e.Handled = False
   
               Case 0
   
                   'prevent zeros as the first character unless followed by the decimal point
                   If TxtLatShift.Text = "0" Then          'Check if there is a zero at the start
                       e.Handled = True                    'If so then prevent further zeros
                   ElseIf TxtLatShift.Text = "-0" Then     'Check if there is a negative zero at the start
                       e.Handled = True                    'If so then prevent further zeros
                   End If
   
   
               Case 1 To 9
   
                   If TxtLatShift.Text = "0" Then
                       TxtLatShift.Text = ""
                   ElseIf TxtLatShift.Text = "-0" Then
                       TxtLatShift.Text = "-"
                   End If
   
                   e.Handled = False
   
               Case ControlChars.Back
   
                   e.Handled = False
   
               Case Else
   
                   e.Handled = True
   
           End Select
   
           'Move the cursor to the end of the text. After this the keystroke inserts the number
           TxtLatShift.Select(TxtLatShift.Text.Length, 0)
   
       End Sub

As I have said this works as the KeyPressEvent of a single Textbox but it doesn't prevent pasting in the wrong format with the mouse right click, which I will have to work on later.

There are four other textboxes that require the same formatting and there may be more as I build the project.

Rather than pasting the same code in all the KeyPressEvents, I thought it would be better to have it as a sub proceedure and call it from each textbox.

I can replace the textbox name with a variable so it can be used with multiple textboxes but the problem is that I don't know how to pass the parameters from the KeyPressEvent to the proceedure or how to use them to change the text in the textboxes, I believe that is in the Handles part but I'm not sure.

I have never used "(sender As Object, e As KeyPressEventArgs) Handles TxtLatShift.KeyPress" before so if somebody could show me what needs to be changed and what it should be changed to, I would greatly appreciate it.

Developer technologies | VB
0 comments No comments
{count} votes

Accepted answer
  1. Dewayne Basnett 1,381 Reputation points
    2023-02-09T14:19:18.19+00:00

    This is your code with just a few changes. I will note that there were errors in your code.

    Adding other textbox .KeyPress events to the method declaration will take care of your requirement. Notice the first line where the sender is Cast to a generic textbox instance that is used throughout the method.

        Private Sub TxtBoxGeneric_KeyPress(sender As Object,
                                            e As KeyPressEventArgs) Handles TxtLatShift.KeyPress, TxtOTHER.KeyPress
    
            Dim TxtBox As TextBox = DirectCast(sender, TextBox) ' <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
            Dim TargetChr As String
            Dim MyPos As String
    
            TargetChr = e.KeyChar
            MyPos = InStr(TxtBox.Text, TargetChr)
    
            Select Case TargetChr
    
                Case "-"
    
                    'Allow only one negative symbol
                    If TxtBox.Text.Length < 1 Then e.Handled = False Else e.Handled = True
    
                Case "."
    
                    'If no character is present this places a "0" before the decimal
                    If TxtBox.Text = "" Then           'Check if the textbox is empty
                        TxtBox.Text = "0"              'Insert a "0" if blank
                    ElseIf TxtBox.Text = "-" Then      'Check if the textbox contains a negative
                        TxtBox.Text = "-0"             'Insert a "-0" if no other number present
                    End If
    
                    'Check for existing decimal point and if found reject extras
                    If MyPos > 0 Then e.Handled = True Else e.Handled = False
    
                Case 0
    
                    'prevent zeros as the first character unless followed by the decimal point
                    If TxtBox.Text = "0" Then          'Check if there is a zero at the start
                        e.Handled = True                    'If so then prevent further zeros
                    ElseIf TxtBox.Text = "-0" Then     'Check if there is a negative zero at the start
                        e.Handled = True                    'If so then prevent further zeros
                    End If
    
    
                Case 1 To 9
    
                    If TxtBox.Text = "0" Then
                        TxtBox.Text = ""
                    ElseIf TxtBox.Text = "-0" Then
                        TxtBox.Text = "-"
                    End If
    
                    e.Handled = False
    
                Case ControlChars.Back
    
                    e.Handled = False
    
                Case Else
    
                    e.Handled = True
    
            End Select
    
            'Move the cursor to the end of the text. After this the keystroke inserts the number
            TxtBox.Select(TxtBox.Text.Length, 0)
    
        End Sub
    
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. LesHay 7,141 Reputation points
    2023-02-09T14:12:47.7333333+00:00

    Hi

    You are asking multiple questions. Best to just ask one per thread.

    Here is some info on using an Event Handler for several controls.

    To handle several controls in one Event Handler is fairly straightforward.

    The Handler needs to know it handles a particular control event, perhaps one of several.

    For example: this is where one handler is set up to handle the KeyPress events for 3 TextBoxes. You can set up a Handler for 1 TextBox and then add each TextBox to the Handles clause manually, or, you can use AddHandler in code. (e.g. AddHandler TextBox3.KeyPress, AddressOf TextBox_KeyPress). To actually work on a particular control from a selection of controls, use a Cast to create the needed control (DirectCast in code below)

    	Private Sub TextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress, TextBox2.KeyPress, TextBox3.KeyPress
    
    Dim tb As TextBox = DirectCast(sender, TextBox)
    
    	End Sub
    
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.