Accessing all the nodes in TreeView Control

I have a TreeView Control with set of nodes and child nodes. For example:

ROOT has A,B,C.

A has a1, a2, a3 and then that a1, a2 also contains some nodes like x1, x2, x3 and so on. Like this many subnodes are there. I know it is possible to use loops with a for loop.

I just want to access all the nodes in TreeView control using one or two for loops.

Is there any algorithm for that or is there any other way?

One more question: Is it is possible to have the path of a tree node in an object or in a string using any library functions? For example:

string S = TreeView1.Nodes[i].Nodes[j].Nodes

Solution 1:

Don't use nested loops, but go for an recursive solution like:

void ListNodes( TreeNode node )
{
  foreach( var subnode in node.Nodes )
  {
    ListNodes( subnode );
  }
  // Print out node
}

Call this function for your root node.

For your additional question: check the FullPath property.

Solution 2:

You can use a recursive function to traverse the whole tree:

private void Traverse(TreeNodeCollection nodes)
{
    foreach (TreeNode node in nodes)
    {
        Console.WriteLine("{0} -> {1}", node.Name, node.FullPath);
        Traverse(node.Nodes);
    }
}

You can then call this using:

Traverse(treeView.Nodes);

and it will walk the whole tree depth first (ie. going down as deep as it can before moving to the next sibling). Passing in the Nodes collection means that this code will deal with trees that have multiple root nodes.

The example code above will print out the name of the node as well as the full path of that node within the tree.

Solution 3:

I am not the biggest fan of recursion but it seems you must use it. I saw a clever example online mixing recursion with an iterator.

    private int GetLevels(TreeNodeCollection treeNodes)
    {
        int level = 0;
        foreach (TreeNode node in TreeTopDown(treeNodes))
        {
            int i = node.Level;
            if (i > level) level = i;
        }
        return level;
    }

    //TopDown Iterator 
    private IEnumerable<TreeNode> TreeTopDown(TreeNodeCollection treeNodes)
    {
        foreach (TreeNode node in treeNodes)
        {
            yield return node;
            foreach (TreeNode subNode in TreeTopDown(node.Nodes)) yield return subNode;               
        }
    }

    //BottomUp Iterator
    private IEnumerable<TreeNode> TreeBottomUp(TreeNodeCollection treeNodes)
    {
        foreach (TreeNode node in treeNodes)
        {
            foreach (TreeNode subNode in TreeBottomUp(node.Nodes)) yield return subNode;
            yield return node;
        }
    }