Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list of all tree nodes (in all levels) in TreeView Controls

How can I get a list of all tree nodes (in all levels) in a TreeView control?

like image 497
Mahmoud Farahat Avatar asked Jan 15 '11 20:01

Mahmoud Farahat


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.

How many root nodes can a TreeView control have?

A typical tree structure has only one root node; however, you can add multiple root nodes to the TreeView control. The Nodes property can also be used to manage the root nodes in the tree programmatically. You can add, insert, remove, and retrieve TreeNode objects from the collection.

How do I get data from TreeView database?

Populating TreeView from database Inside the PopulateTreeView method, a loop is executed over the DataTable and if the ParentId is 0 i.e. the node is a parent node, a query is executed over the VehicleSubTypes table to populate the corresponding child nodes and again the PopulateTreeView method is called.

Which property in the TreeView control represent the node?

The key properties of the TreeView control are Nodes and SelectedNode. The Nodes property contains the list of top-level nodes in the tree view. The SelectedNode property sets the currently selected node.


1 Answers

Assuming you have a tree with one root node the following code will always loop the tree nodes down to the deepest, then go one level back and so on. It will print the text of each node. (Untested from the top of my head)

TreeNode oMainNode = oYourTreeView.Nodes[0];
PrintNodesRecursive(oMainNode);

public void PrintNodesRecursive(TreeNode oParentNode)
{
  Console.WriteLine(oParentNode.Text);

  // Start recursion on all subnodes.
  foreach(TreeNode oSubNode in oParentNode.Nodes)
  {
    PrintNodesRecursive(oSubNode);
  }
}
like image 183
Krumelur Avatar answered Sep 28 '22 02:09

Krumelur