Handling multiple textboxes, as per 'old' VB6 txtBox(Index)

J Trahair

Well-known member
Joined
May 14, 2008
Messages
175
Location
Spain
Programming Experience
10+
In old VB6, I could set all txtBox controls when members of the same index eg. txtBox(0), txtBox(1) etc., to all do certain things in a couple of lines of code, eg.
VB.NET:
Private Sub txtBox_GotFocus(Index As Integer)
    txtBox(Index).SelStart = 0
    txtBox(Index).SelLength = Len(txtBox(Index))
End Sub
in this case, every time the focus enters a txtBox, the value appears in a blue highlight with the cursor at the end. This gives consistent behaviour in all txtBoxes, not just with GotFocus, but trapping of keyboard characters and Enter, etc.

Seeing as how VB2005 Pro doesn't allow TextBoxes to belong to an Indexed collection, how do I handle consistency without a separate event for each TextBox for each property/method? Just imagine I might have 48 TextBoxes.

Thanks in advance.
 
Select all the textboxes and find the event in properties window, doubleclick it or write a event handler name. This will add one event handler for all selected controls. Here is an example where I have selected two textboxes and named an event handler "TextBoxes_Enter" for Enter event:
VB.NET:
Private Sub TextBoxes_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.Enter, TextBox1.Enter
    CType(sender, TextBox).SelectAll()
End Sub
In .Net all events follow same pattern, the sender parameter is always the object instance that raised the event, here in this example we know it is a TextBox and cast it to this type to call the SelectAll instance method.

If the controls is added dynamically in code you can similarly add multiple event handlers with the AddHandler statement.
 
Not sure if this is the best way to do it, but you could try :-

VB.NET:
Public Class Form1

    Public Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        For Each _Control As Control In Me.Controls
            If TypeOf _Control Is TextBox Then
                AddHandler _Control.Enter, AddressOf AnyTextBox_Enter
            End If
        Next

    End Sub

    Private Sub AnyTextBox_Enter(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim _ActiveTextBox As TextBox = CType(sender, TextBox)
        _ActiveTextBox.SelectAll()
    End Sub

End Class
 
Back
Top