• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1130
  • Last Modified:

C# TreeView Question

How to traverse a TreeView in C# Windows Form and list all the leaf nodes in the tree?
1 Solution
TreeView.Nodes gives you a collection of TreeNode objects.  A TreeNode object has a number of children (Nodes property).  If if has no nodes, it is a child.

Let's write some recursive code to do this:

If we visit a tree node and the child nodes are zero in size, we have a leaf.  In this case we print out some representation of the tree node.  Otherwise we visit each of the child nodes in turn.

// We start things off like this in whatever method you want, like traverse.
foreach (TreeNode treeNode in treeView1.Nodes)
  visit( treeNode );

We then define a visitor type pattern. [see http://en.wikipedia.org/wiki/Visitor_pattern ]

private void visit( TreeNode treeNode )
  if (treeNode.Nodes.Count == 0)
    // If we want to make this more general, we might have a processor interface passed into this
    // and do something like processor.accept( treeNode ), but here we'll just print it out :)
    foreach (TreeNode t in treeNode.Nodes)

Obviously it'd be trivial to adapt this to return a list of leaf nodes.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now