Question

VB2010 I have a pretty good routine in the NodeMouseClick of a Treeview that hides/displays panels in the form depending on what node is clicked by the user. The simplified version:

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

My problem is on form load I want a default node selected or actually the things done as if the user clicked the default node.

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

The .SelectedNode doesn't do this and am trying to figure out how to do this in .NET. In VB6 I used to use tvw_NodeClick tvw.Nodes("gen").

Était-ce utile?

La solution

You could just call tvw_NodeMouseClick() directly, no point in trying to get the event to fire. But that's a bit annoying because of the arguments. Simply refactor the code and break out the parts you want to re-use:

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

Now it is trivial:

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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top