缩短代码vb.net

时间:2018-01-14 10:32:55

标签: vb.net

是否可以缩短这些代码?如果有,怎么样?谢谢你的回答。

    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 个答案:

答案 0 :(得分:1)

由于您的标签和文本框基本上具有相同的名称(它只是前缀不同),您可以:

  1. 将所有GetFocus事件绑定到单个事件处理程序。

  2. 获取sender的名称(sender是引发事件的控件),删除txt前缀并将其替换为lbl }。

  3. 按新名称(lbl...)查找控件。

  4. 如果找到,请将其显示。

  5. 在代码中,它看起来像这样:

    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