Search code examples
c#winformstreeviewparent-node

c# Obtain a list of TreeView Parent nodes


If I have a TreeView (myTreeview),how can I obtain a list of all the nodes that are parent nodes? i.e. nodes that have children


Solution

  • myTreeview.Nodes will give you a list of root nodes as defined by MS which basically means nodes on the root branch of the tree.

    This code will build a list of root nodes with children:

        IList<TreeNode> nodesWithChildren = new List<TreeNode>();
        foreach( TreeNode node in myTreeview.Nodes )
            if( node.Nodes.Count > 0 ) nodesWithChildren.Add( node );
    

    Update: and if you wanted all nodes in the TreeView that had a child regardless of how deep into the tree then use a bit of recursion, e.g.

    private static IList<TreeNode> BuildParentNodeList(TreeView treeView)
    {
        IList<TreeNode> nodesWithChildren = new List<TreeNode>();
    
        foreach( TreeNode node in treeView.Nodes  )
            AddParentNodes(nodesWithChildren, node);
    
        return nodesWithChildren;
    }
    
    private static void AddParentNodes(IList<TreeNode> nodesWithChildren, TreeNode parentNode)
    {
        if (parentNode.Nodes.Count > 0)
        {
            nodesWithChildren.Add( parentNode );
            foreach( TreeNode node in parentNode.Nodes )
                AddParentNodes( nodesWithChildren, node );
        }
    }
    

    Update 2: Recursion method with only 1 foreach loop:

    private static IList<TreeNode> BuildParentNodeList(TreeView treeView)
    {
        IList<TreeNode> nodesWithChildren = new List<TreeNode>();
        AddParentNodes( nodesWithChildren, treeView.Nodes );
        return nodesWithChildren;
    }
    
    private static void AddParentNodes(IList<TreeNode> nodesWithChildren, TreeNodeCollection parentNodes )
    {
        foreach (TreeNode node in parentNodes)
        {
            if (node.Nodes.Count > 0)
            {
                nodesWithChildren.Add( node );
                AddParentNodes(nodesWithChildren, node.Nodes);
            }
        }
    }