vb.net的treeview点击节点折叠其它分支

时间:2024-03-12 14:35:50

vb的treeview控件如何实现点击任意节点,只保留从根目录到当前选择的节点都打开,其他节点关闭?

我的思路是先折叠所有节点,然后循环找点击节点的父节点,一个个展开它们。

Private Sub TreeView1_AfterSelect(sender As Object, e As TreeViewEventArgs) Handles TreeView1.AfterSelect
    Dim myNode As TreeNode
    myNode = Me.TreeView1.SelectedNode
    Me.TreeView1.CollapseAll()
    Do While Not (IsNothing(myNode))
        myNode.Expand()

        myNode = myNode.Parent

    Loop
End Sub

我解释一下代码:

TreeView1_AfterSelect是treeview节点被点击事件触发的方法,myNode=Me.TreeView1.SelectedNode将被点击节点赋值给myNode。Not(IsNothing(myNode))判断myNode是否为空,myNode.Expand()展开节点myNode。myNode.Parent获取myNode的父节点。