Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List all child nodes of a parent node in a treeview control in Visual C#

Tags:

c#

treeview

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.

like image 864
user975696 Avatar asked Oct 02 '11 18:10

user975696


People also ask

How do I get all child nodes of TreeView in VB net?

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.

Which method is used to add child node in TreeView control?

To add nodes programmatically Use the Add method of the tree view's Nodes property.

How many child nodes can a parent node have?

In a binary search tree, parent nodes can have a maximum of two children.

Which property in the TreeView control represents the node?

The TreeNode class represents a node of a TreeView.


2 Answers

public IEnumerable<TreeNode> GetChildren(TreeNode Parent)
{
    return Parent.Nodes.Cast<TreeNode>().Concat(
           Parent.Nodes.Cast<TreeNode>().SelectMany(GetChildren));
}
like image 152
Magnus Avatar answered Nov 14 '22 02:11

Magnus


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]);
like image 33
David Heffernan Avatar answered Nov 14 '22 02:11

David Heffernan