How to get a list of all child nodes in a TreeView in .NET

后端 未结 10 1082
抹茶落季
抹茶落季 2020-12-15 21:28

I have a TreeView control in my WinForms .NET application that has multiple levels of childnodes that have childnodes with more childnodes, with no defined depth. When a use

相关标签:
10条回答
  • 2020-12-15 21:52

    I have an extension method that I use for this:

    public static IEnumerable<TreeNode> DescendantNodes( this TreeNode input ) {
        foreach ( TreeNode node in input.Nodes ) {
            yield return node;
            foreach ( var subnode in node.DescendantNodes() )
                yield return subnode;
            }
    }
    

    It's C#, but could be referenced from VB or converted to it.

    0 讨论(0)
  • 2020-12-15 21:59

    in .Net WindowsForm TreeView has Find() method with the optional flag 'searchAllChildren'.

    in asp.net instead there isn't. to have the same result i use this (similar to Keith answer, but in input i use the TreeView)

    public static IEnumerable<TreeNode> DescendantNodes2(this TreeView input)
    {
        foreach (TreeNode node in input.Nodes)
        {
            yield return node;
            foreach (var subnode in node.DescendantNodes())
                yield return subnode;
        }
    }
    private static IEnumerable<TreeNode> DescendantNodes(this TreeNode input)
    {
        foreach (TreeNode node in input.ChildNodes)
        {
            yield return node;
            foreach (var subnode in node.DescendantNodes())
                yield return subnode;
        }
    }
    
    0 讨论(0)
  • 2020-12-15 22:03

    Use recursion

    Function GetChildren(parentNode as TreeNode) as List(Of String)
      Dim nodes as List(Of String) = New List(Of String)
      GetAllChildren(parentNode, nodes)
      return nodes
    End Function
    
    Sub GetAllChildren(parentNode as TreeNode, nodes as List(Of String))
      For Each childNode as TreeNode in parentNode.Nodes
        nodes.Add(childNode.Text)
        GetAllChildren(childNode, nodes)
      Next
    End Sub
    
    0 讨论(0)
  • 2020-12-15 22:05

    I have converted the code to VB.Net with this as a result:

    Public Function FlattenBreadth(ByVal tree As TreeView) As List(Of TreeNode)
        Dim nodes As New List(Of TreeNode)
        Dim queue As New Queue(Of TreeNode)
        Dim top As TreeNode
        Dim nod As TreeNode
        For Each top In tree.Nodes
            queue.Enqueue(top)
        Next
        While (queue.Count > 0)
            top = queue.Dequeue
            nodes.Add(top)
            For Each nod In top.Nodes
                queue.Enqueue(nod)
            Next
        End While
        FlattenBreadth = nodes
    End Function
    
    0 讨论(0)
提交回复
热议问题