Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...