I have a treeview control, and it contains a single parent node and several child nodes from that parent. Is there a way to obtain an array or list of all the child nodes from the main parent? i.e. getting all the nodes from treeview.nodes[0], or the first parent node.
3 Answers
9
votes
You can add to a list recursively like this:
public void AddChildren(List<TreeNode> Nodes, TreeNode Node)
{
foreach (TreeNode thisNode in Node.Nodes)
{
Nodes.Add(thisNode);
AddChildren(Nodes, thisNode);
}
}
Then call this routine passing in the root node:
List<TreeNode> Nodes = new List<TreeNode>();
AddChildren(Nodes, treeView1.Nodes[0]);
9
votes
-2
votes
You could do something like this .. to get the all nodes in tree view ..
private void PrintRecursive(TreeNode treeNode)
{
// Print the node.
System.Diagnostics.Debug.WriteLine(treeNode.Text);
MessageBox.Show(treeNode.Text);
// Print each node recursively.
foreach (TreeNode tn in treeNode.Nodes)
{
PrintRecursive(tn);
}
}
// Call the procedure using the TreeView.
private void CallRecursive(TreeView treeView)
{
// Print each node recursively.
TreeNodeCollection nodes = treeView.Nodes;
foreach (TreeNode n in nodes)
{
PrintRecursive(n);
}
}
would you pls take alook at this link .