How can I get a list of all tree nodes (in all levels) in a TreeView
control?
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.
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.
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.
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.
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);
}
}
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