代码之家  ›  专栏  ›  技术社区  ›  Nostromo

按排序顺序获取TreeView节点

  •  0
  • Nostromo  · 技术社区  · 6 年前

    我们有一个用VB6编写的传统应用程序,使用默认的Microsoft TreeView 树景 我们考虑为用户实现一个小的过滤/搜索功能。

    第一次尝试是切换可见性,只使节点(及其父节点)可见,与定义的搜索匹配。但这是不可能的,因为默认的微软 树景 控件不允许其节点可见或不可见。

    因此,第二个尝试是遍历树中的所有节点,并确保当节点与定义的搜索匹配时节点的可见性(并停止遍历)。当找到的节点不是用户要查找的节点时,他可以“继续”搜索并查找下一个符合条件的节点。

    到目前为止,除了一个小问题外,这个方法非常有效。搜索不是从上到下进行的,因为树是按随机排序顺序填充数据,然后通过设置 Sorted 每个节点的属性(旧代码)。所以搜索是通过随机添加的节点,找到的节点在顶层节点( Nodes 树景

    有没有办法按照显示给用户的顺序获取树的所有节点?我不想更改用数据填充树并在将数据添加到 树景 可能会影响性能。

    VB6

    以下是我目前为止的搜索代码:

    Private Sub cmdSearch_Click()
        Dim oMatch As Node
    
        Set oMatch = GetNextMatch
    
        If Not (oMatch Is Nothing) Then
            oMatch.EnsureVisible
            oMatch.Selected = True
            Me.TreeView1.SelectedItem = oMatch
            Me.TreeView1.SetFocus
        End If
    
    End Sub
    
    Private Function GetNextMatch() As Node
        Dim lIndex As Long
        Dim oResult As Node
    
        For lIndex = mlLastFoundIndex + 1 To Me.TreeView1.Nodes.Count
            If IsMatch(Me.TreeView1.Nodes(lIndex).Text) Then
                Set oResult = Me.TreeView1.Nodes(lIndex)
                mlLastFoundIndex = lIndex
                Exit For
            End If
        Next lIndex
    
        Set GetNextMatch = oResult
    End Function
    
    Private Sub txtSearch_Change()
        mlLastFoundIndex = 0
    End Sub
    
    0 回复  |  直到 6 年前
        1
  •  0
  •   Steve Coan    6 年前

    与其按整数遍历treeviewnodes集合,不如使用Child和Next属性来完成您的请求。以下代码将按所选节点在TreeView控件中的出现顺序打印这些子节点:

    Private Sub Command3_Click()
      If Not TreeView1.SelectedItem Is Nothing Then
        PrintNodesInSortedOrder TreeView1.SelectedItem
      End If
    End Sub
    
    Private Sub PrintNodesInSortedOrder(ParentNode As MSComctlLib.Node)
      Dim Nod As MSComctlLib.Node
    
      Set Nod = ParentNode.Child
      Do While Not Nod Is Nothing
        Debug.Print Nod.Text
        Set Nod = Nod.Next
      Loop
    
    End Sub