Shorten code vb.net

Is it possible to shorten these codes? If yes, how? Thanks for your answer guys.

    Private Sub txtFirstName_GotFocus(sender As Object, e As EventArgs) Handles txtFirstName.GotFocus
        lblFirstName.Visible = True
    End Sub

    Private Sub txtLastName_GotFocus(sender As Object, e As EventArgs) Handles txtLastName.GotFocus
        lblLastName.Visible = True
    End Sub

    Private Sub txtMiddleName_GotFocus(sender As Object, e As EventArgs) Handles txtMiddleName.GotFocus
        lblMiddleName.Visible = True
    End Sub

    Private Sub txtAddress_GotFocus(sender As Object, e As EventArgs) Handles txtAddress.GotFocus
        lblAddress.Visible = True
    End Sub

    Private Sub txtContact_GotFocus(sender As Object, e As EventArgs) Handles txtContact.GotFocus
        lblContact.Visible = True
    End Sub

1 answer

  • answered 2018-01-14 11:00 Visual Vincent

    Since your labels and text boxes essentially have the same name (it's only the prefix that's different) you can:

    1. Bind all GetFocus events to a single event handler.

    2. Get the sender's name (sender is the control that raised the event), remove the txt prefix and replace it with lbl.

    3. Look for a control by the new name (lbl...).

    4. If found, make it visible.

    In code it'd look like this:

    Private Sub TextBoxes_GotFocus(sender As Object, e As EventArgs) Handles txtFirstName.GotFocus, txtLastName.GotFocus, txtMiddleName.GotFocus, txtAddress.GotFocus, txtContact.GotFocus
        Const NamePrefix As String = "txt"
        Const NewPrefix As String = "lbl"
    
        Dim ctrl As Control = TryCast(sender, Control)
        If ctrl IsNot Nothing AndAlso ctrl.Name.StartsWith(NamePrefix) Then 'Check if the sender's name starts with our prefix.
            Dim NewName As String = NewPrefix & ctrl.Name.Remove(0, NamePrefix.Length) 'Remove the old prefix and replace it with the new one.
            Dim Controls As Control.ControlCollection = Me.Controls.Find(NewName, True) 'Look for the control of our new name.
    
            If Controls.Count > 0 Then 'Did we find one?
                Controls(0).Visible = True 'Make it visible.
            End If
        End If
    End Sub