c# Obtain a list of TreeView Parent nodes

2019-07-13 16:44发布

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

2条回答
三岁会撩人
2楼-- · 2019-07-13 17:27

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);
        }
    }
}
查看更多
爷、活的狠高调
3楼-- · 2019-07-13 17:43
private void AddNonLeafNodes(List<TreeNode> nonLeafNodes, TreeNodeCollection nodes)
{
    foreach( TreeNode node in nodes )
    {
        if( node.Nodes.Count > 0 )
        {
            nonLeafNodes.Add(node);
            AddNonLeafNodes(nonLeafNodes,node.Nodes);
        }
    }
}

List<TreeNode> nonLeafNodes = new List<TreeNode>();
AddNonLeafNodes(nonLeafNodes,treeView1.Nodes);
查看更多
登录 后发表回答