Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
163 views
Welcome To Ask or Share your Answers For Others

1 Answer

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() = Me.Controls.Find(NewName, True) 'Look for the control of our new name.

        If Controls.Length > 0 Then 'Did we find one?
            Controls(0).Visible = True 'Make it visible.
        End If
    End If
End Sub

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...