.NET模拟Treeview中的NodeMouseClick

时间:2013-10-11 19:00:24

标签: .net click treeview treenode mouseclick-event

VB2010我在Treeview的NodeMouseClick中有一个非常好的例程,它根据用户点击的节点隐藏/显示表单中的面板。简化版:

Private Sub tvw_NodeMouseClick(sender As Object, e As System.Windows.Forms.TreeNodeMouseClickEventArgs) Handles tvw.NodeMouseClick
        Dim pNode As TreeNode = e.Node      'get the node that was clicked
        Dim nodeName As String = pNode.Name 'get the name of the node

        Select Case nodeName.ToLower
            Case "gen"
                pnlGeneral.Visible = True
                pnlOrigin.Visible = False
            Case "ogn"
                pnlGeneral.Visible = False
                pnlOrigin.Visible = True
            Case Else
                'do nothing
        End Select
End Sub

我的问题在于表单加载我希望选择一个默认节点,或者实际完成的事情,就好像用户点击了默认节点一样。

Private Sub frm_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        'initialize the treeview
        With tvw
            .Nodes.Add("gen", "General", "gen", "gen")
            .Nodes.Add("ogn", "Origin", "ogn", "ogn")
            .SelectedNode = .Nodes.Item("gen")
        End With
End Sub

.SelectedNode没有这样做,我试图弄清楚如何在.NET中执行此操作。在VB6中,我曾经使用tvw_NodeClick tvw.Nodes(“gen”)。

1 个答案:

答案 0 :(得分:1)

您可以直接调用tvw_NodeMouseClick(),尝试触发事件没有意义。但由于争论,这有点烦人。只需重构代码并打破您想要重复使用的部分:

Private Sub NodeSelect(pNode As TreeNode)
    Dim nodeName As String = pNode.Name ''get the name of the node

    Select Case nodeName.ToLower
        Case "gen"
            pnlGeneral.Visible = True
            pnlOrigin.Visible = False
        Case "ogn"
            pnlGeneral.Visible = False
            pnlOrigin.Visible = True
        Case Else
            ''do nothing
    End Select
End Sub

Private Sub tvw_NodeMouseClick(sender As Object, e As System.Windows.Forms.TreeNodeMouseClickEventArgs) Handles tvw.NodeMouseClick
    NodeSelect(e.Node)
End Sub

现在很简单:

Private Sub frm_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    With tvw
        Dim node = .Nodes.Add("gen", "General", "gen", "gen")
        .Nodes.Add("ogn", "Origin", "ogn", "ogn")
        .SelectedNode = node
        NodeSelect(node)
    End With
End Sub