?
Solved

C# TreeView Question

Posted on 2006-06-19
1
Medium Priority
?
1,128 Views
Last Modified: 2012-08-13
How to traverse a TreeView in C# Windows Form and list all the leaf nodes in the tree?
0
Comment
Question by:michellechan57
1 Comment
 
LVL 4

Accepted Solution

by:
fffej78 earned 500 total points
ID: 16933034
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 :)
    System.Console.WriteLine(treeNode.ToString());
  }
  else
  {
    foreach (TreeNode t in treeNode.Nodes)
    {
      visit(t);
    }
  }
}

Obviously it'd be trivial to adapt this to return a list of leaf nodes.
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

High user turnover can cause old/redundant user data to consume valuable space. UserResourceCleanup was developed to address this by automatically deleting user folders when the user account is deleted.
Hello there! As a developer I have modified and refactored the unit tests which was written by fellow developers in the past. On the course, I have gone through various misconceptions and technical challenges when it comes to implementation. I would…
this video summaries big data hadoop online training demo (http://onlineitguru.com/big-data-hadoop-online-training-placement.html) , and covers basics in big data hadoop .
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
Suggested Courses

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question