Solved

C# TreeView Question

Posted on 2006-06-19
1
1,073 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 125 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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

759 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now