Create an Event Handler for multiple textboxes

José Carlos 886 Reputation points
2023-08-23T18:58:35.29+00:00

Guys.

I have a Panel with 15 textbox.

I would like when these textboxes have values, when I press the tab key to move to the next or previous textbox, the content is marked. I made a method for each textbox. As there are 15, I would like to make only one method using some event that does what I want, like an event handler in the textbox. I just don't know how to do that. The method for each textbox I got is like this:

    Private Sub TextBox4_GotFocus(sender As Object, e As EventArgs) Handles textBox4.GotFocus
        textBox4.SelectAll()
    End Sub

    Private Sub TextBox5_GotFocus(sender As Object, e As EventArgs) Handles textBox5.GotFocus
        textBox5.SelectAll()
    End Sub
    Private Sub TextBox6_GotFocus(sender As Object, e As EventArgs) Handles textBox6.GotFocus
        textBox6.SelectAll()
    End Sub
Developer technologies | VB
Developer technologies | Visual Studio | Other
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2023-08-23T19:45:58.6333333+00:00

    Hi

    Here is some code that may help.

    The code in the Form Load event assigns all the TextBoxes in Panel1 ENTER EVENT to the same Sub (TextBox_Enter)

    I chose the Enter Event as the GotFocus fires for all TextBoxes if the Panel was obscured by (say) another window and then made visible again.

    	Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
    		' This is maybe what you want - this will
    		' add all TextBoxes in Panel1 Enter event
    		' to the same Handler
    		For Each c As Control In Panel1.Controls
    			If c.GetType = GetType(TextBox) Then
    				AddHandler c.Enter, AddressOf TextBox_Enter
    			End If
    		Next
    	End Sub
    
    	Private Sub TextBox_Enter(sender As Object, e As EventArgs)
    		' Handles all Panel1 TextBoxes Enter Event
    		Dim tb As TextBox = DirectCast(sender, TextBox)
    		tb.SelectAll()
    	End Sub
    
    
    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful

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.