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.
Solution: In a NodeSelectedEvent event, the event argument (e) holds the object of the selected node – Node. The selected node object have property called Items, it holds a list of child node object of the selected node. By iterating the Item object, you can get the information of each child node.
To add nodes programmatically Use the Add method of the tree view's Nodes property.
In a binary search tree, parent nodes can have a maximum of two children.
The TreeNode class represents a node of a TreeView.
public IEnumerable<TreeNode> GetChildren(TreeNode Parent)
{
return Parent.Nodes.Cast<TreeNode>().Concat(
Parent.Nodes.Cast<TreeNode>().SelectMany(GetChildren));
}
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With