简体   繁体   English

c#获取TreeView父节点列表

[英]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? 如果我有TreeView(myTreeview),如何获取作为父节点的所有节点的列表? ie nodes that have children 即有孩子的节点

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. myTreeview.Nodes将为您提供由MS定义的根节点列表,这基本上意味着树的根分支上的节点。

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, eg 更新:如果您想要TreeView中所有有子节点的节点,无论它在树中有多深,都可以使用一些递归,例如

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: 更新2:仅1个foreach循环的递归方法:

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);
        }
    }
}
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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM