Get a list of all tree nodes (in all levels) in TreeView Controls
You can use two recursive extension methods. You can either call myTreeView.GetAllNodes()
or myTreeNode.GetAllNodes()
:
public static List<TreeNode> GetAllNodes(this TreeView _self)
{
List<TreeNode> result = new List<TreeNode>();
foreach (TreeNode child in _self.Nodes)
{
result.AddRange(child.GetAllNodes());
}
return result;
}
public static List<TreeNode> GetAllNodes(this TreeNode _self)
{
List<TreeNode> result = new List<TreeNode>();
result.Add(_self);
foreach (TreeNode child in _self.Nodes)
{
result.AddRange(child.GetAllNodes());
}
return result;
}
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);
}
}