c#获取TreeView父节点列表 [英] c# Obtain a list of TreeView Parent nodes
问题描述
如果我有一个 TreeView (myTreeview),我如何获得所有作为父节点的节点的列表?即有孩子的节点
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
推荐答案
myTreeview.Nodes 会给你一个由 MS 定义的根节点列表,基本上意味着树的根分支上的节点.
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 );
<小时>
更新:如果您希望 TreeView 中的所有节点都有一个孩子,而不管树的深度如何,那么请使用一些递归,例如
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 );
}
}
<小时>
更新 2:只有 1 个 foreach 循环的递归方法:
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);
}
}
}
这篇关于c#获取TreeView父节点列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!