c#获取TreeView Parent节点列表

时间:2009-02-18 11:11:23

标签: c# winforms treeview parent-node

如果我有TreeView(myTreeview),我如何获得作为父节点的所有节点的列表?即有孩子的节点

2 个答案:

答案 0 :(得分:5)

myTreeview.Nodes将为您提供MS定义的根节点列表,它基本上是指树的根分支上的节点。

此代码将构建一个包含子节点的根节点列表:

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

更新:如果您希望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 );
    }
}

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

答案 1 :(得分:1)

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