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
A:
Traverse the tree and build a list of the leaf nodes. The nodes you asked for are everything except the leaf nodes.
Mitch Wheat
2009-02-18 11:21:24
+4
A:
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);
}
}
}
ng5000
2009-02-18 11:25:03
Thanks for the comprehensive answer! I would +10 if posible!
TK
2009-02-18 11:42:59
Thanks, much appreciated :)
ng5000
2009-02-18 11:44:04
A:
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);