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

- 7,287
- 7
- 50
- 85

- 5,364
- 4
- 43
- 59
9 Answers
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;
}

- 10,906
- 9
- 64
- 105
-
2runs for me changing `_self.ChildNodes` by `_self.Nodes`. Remember to write this two methods into a new static class: `public static class TreeViewExtensions`. – dani herrera May 14 '19 at 09:08
-
@daniherrera Thanks, I fixed the mistake. Not sure why I used `ChildNodes` in the first place. – Martin Braun May 14 '19 at 09:11
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);
}
}

- 7,946
- 15
- 57
- 87

- 32,180
- 27
- 124
- 263
Lazy LINQ approach, just in case you're looking for something like this:
private void EnumerateAllNodes()
{
TreeView myTree = ...;
var allNodes = myTree.Nodes
.Cast<TreeNode>()
.SelectMany(GetNodeBranch);
foreach (var treeNode in allNodes)
{
// Do something
}
}
private IEnumerable<TreeNode> GetNodeBranch(TreeNode node)
{
yield return node;
foreach (TreeNode child in node.Nodes)
foreach (var childChild in GetNodeBranch(child))
yield return childChild;
}

- 10,890
- 8
- 45
- 54
Update to Krumelur's answer (replace 2 first lines of his/her solution with this):
foreach ( var node in oYourTreeView.Nodes )
{
PrintNodesRecursive( node );
}

- 4,721
- 1
- 25
- 20
-
Yeah, then it will spit out all subtrees if there are several roots. But really: a tree with several nodes is a really seldom in nature :-) Oh, and it's "his" ;) – Krumelur Jan 15 '11 at 21:17
-
In fact, in nature this is a quite common phaenommena :) In programming I can imagine a few scenarios where it is useful. For example: treeview containing departments of a company, each having subdepartments and so on. You probably won't have any superdepartment. – dzendras Jan 15 '11 at 21:24
-
1Sorry guys but you both need to edit your answers. @Krumelur your foreach is misspelled and dzendras, your 'var' is not correct. Shouldn't it be a cast of somesort to TreeNode? In C# var is not recognised. – Fandango68 Apr 22 '15 at 01:12
-
Though it is true that var is recognized by the new C# compiler, it has to know the type to work correctly and Nodes is IEnumerable, not IEnumerable
and so will be typed as object. – bkqc May 29 '19 at 13:39
Because TreeView has many levels, do recursive function:
public void AddNodeAndChildNodesToList(TreeNode node)
{
listBox1.Items.Add(node.Text); // Adding current nodename to ListBox
foreach (TreeNode actualNode in node.Nodes)
{
AddNodeAndChildNodesToList(actualNode); // recursive call
}
}
Than call this function for all first level Nodes in TreeView:
foreach (TreeNode actualNode in treeView1.Nodes) // Begin with Nodes from TreeView
{
AddNodeAndChildNodesToList(actualNode);
}
Code is from site C# TreeView

- 21
- 3
I think my solution is more elegant, it uses generics (because TreeView can store each kind of objects derived from TreeNode) and has a single function recursively called. It should be straightforward also convert this as extension.
List<T> EnumerateAllTreeNodes<T>(TreeView tree, T parentNode = null) where T : TreeNode
{
if (parentNode != null && parentNode.Nodes.Count == 0)
return new List<T>() { };
TreeNodeCollection nodes = parentNode != null ? parentNode.Nodes : tree.Nodes;
List<T> childList = nodes.Cast<T>().ToList();
List<T> result = new List<T>(1024); //Preallocate space for children
result.AddRange(childList); //Level first
//Recursion on each child node
childList.ForEach(n => result.AddRange(EnumerateAllTreeNodes(tree,n)));
return result;
}
The usage is straightforward, just call:
List<MyNodeType> allnodes = EnumerateAllTreeNodes<MyNodeType>(tree);

- 361
- 2
- 5
If you need some processing across all nodes of a treeview, you could use a stack rather than recursive methods:
Stack<TreeNode> nodeStack = new Stack<TreeNode>(treeview1.Nodes.Cast<TreeNode>());
while(nodeStack.Count > 0)
{
TreeNode node = nodeStack.Pop();
// Do your processing on the node here...
// Add all children to the stack
if(node.Nodes.Count > 0)
foreach(TreeNode child in node.Nodes)
nodeStack.Push(child);
}

- 31
- 3
This code help you to iterate though all TreeView list with identifying current depth level. Code can be used to save TreeView items to XML file and other purposes.
int _level = 0;
TreeNode _currentNode = treeView1.Nodes[0];
do
{
MessageBox.Show(_currentNode.Text + " " + _level);
if (_currentNode.Nodes.Count > 0)
{
_currentNode = _currentNode.Nodes[0];
_level++;
}
else
{
if (_currentNode.NextNode != null)
_currentNode = _currentNode.NextNode;
else
{
_currentNode = _currentNode.Parent.NextNode;
_level--;
}
}
}
while (_level > 0);

- 1,740
- 1
- 15
- 11