0 out of 1 rated this helpful - Rate this topic

How to: Iterate Through All Nodes of a Windows Forms TreeView Control

It is sometimes useful to examine every node in a Windows Forms TreeView control in order to perform some calculation on the node values. This operation can be done using a recursive procedure (recursive method in C# and C++) that iterates through each node in each collection of the tree.

Each TreeNode object in a tree view has properties that you can use to navigate the tree view: FirstNode, LastNode, NextNode, PrevNode, and Parent. The value of the Parent property is the parent node of the current node. The child nodes of the current node, if there are any, are listed in its Nodes property. The TreeView control itself has the TopNode property, which is the root node of the entire tree view.

To iterate through all nodes of the TreeView control

  1. Create a recursive procedure (recursive method in C# and C++) that tests each node.

  2. Call the procedure.

    The following example shows how to print each TreeNode object's Text property:

    Private Sub PrintRecursive(ByVal n As TreeNode)
       System.Diagnostics.Debug.WriteLine(n.Text)
       MessageBox.Show(n.Text)
       Dim aNode As TreeNode
       For Each aNode In n.Nodes
          PrintRecursive(aNode)
       Next
    End Sub
    
    ' Call the procedure using the top nodes of the treeview.
    Private Sub CallRecursive(ByVal aTreeView As TreeView)
       Dim n As TreeNode
       For Each n In aTreeView.Nodes
          PrintRecursive(n)
       Next
    End Sub
    
    

    private void PrintRecursive(TreeNode treeNode)
    {
       // Print the node.
       System.Diagnostics.Debug.WriteLine(treeNode.Text);
       MessageBox.Show(treeNode.Text);
       // Print each node recursively.
       foreach (TreeNode tn in treeNode.Nodes)
       {
          PrintRecursive(tn);
       }
    }
    
    // Call the procedure using the TreeView.
    private void CallRecursive(TreeView treeView)
    {
       // Print each node recursively.
       TreeNodeCollection nodes = treeView.Nodes;
       foreach (TreeNode n in nodes)
       {
          PrintRecursive(n);
       }
    }
    
    

    private void PrintRecursive(TreeNode treeNode) 
    {
       // Print the node.
       System.Diagnostics.Debug.WriteLine(treeNode.get_Text());
       MessageBox.Show(treeNode.get_Text());
       for(int i = 0; i < treeNode.GetNodeCount(false); ++i) // Print each node recursively.
       {
          PrintRecursive(treeNode.get_Nodes().get_Item(i));
       }
    }
    
    // Call the procedure using the TreeView.
    private void CallRecursive(TreeView treeView) 
    {
       // Print each node recursively.
       TreeNodeCollection nodes = treeView.get_Nodes();
       for(int i = 0; i < nodes.get_Count(); ++i)
       {
          PrintRecursive(nodes.get_Item(i));
       }
    }
    
    

    private:
       void PrintRecursive( TreeNode^ treeNode )
       {
          // Print the node.
          System::Diagnostics::Debug::WriteLine( treeNode->Text );
          MessageBox::Show( treeNode->Text );
          
          // Print each node recursively.
          System::Collections::IEnumerator^ myNodes = (safe_cast<System::Collections::IEnumerable^>(treeNode->Nodes))->GetEnumerator();
          try
          {
             while ( myNodes->MoveNext() )
             {
                TreeNode^ tn = safe_cast<TreeNode^>(myNodes->Current);
                PrintRecursive( tn );
             }
          }
          finally
          {
             IDisposable^ disposable = dynamic_cast<System::IDisposable^>(myNodes);
             if ( disposable != nullptr )
                      disposable->Dispose();
          }
       }
    
       // Call the procedure using the TreeView.
       void CallRecursive( TreeView^ treeView )
       {
          // Print each node recursively.
          TreeNodeCollection^ nodes = treeView->Nodes;
          System::Collections::IEnumerator^ myNodes = (safe_cast<System::Collections::IEnumerable^>(nodes))->GetEnumerator();
          try
          {
             while ( myNodes->MoveNext() )
             {
                TreeNode^ n = safe_cast<TreeNode^>(myNodes->Current);
                PrintRecursive( n );
             }
          }
          finally
          {
             IDisposable^ disposable = dynamic_cast<System::IDisposable^>(myNodes);
             if ( disposable != nullptr )
                      disposable->Dispose();
          }
       }
    
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
A simple code example
/// <summary>This method returns the nodes in the tree flattened to a list
        /// in a depth first manner.
        /// It is a also an extension method on teh TreeNodeCollection class.
        /// </summary>
        /// <param name="nodColl"></param>
        /// <returns></returns>
        public static List<TreeNode> GetNodeList(this TreeNodeCollection nodColl)
        {
            var ret = new List<TreeNode>();
            foreach (TreeNode node in nodColl)
            {
                ret.Add(node);
                ret.AddRange(node.Nodes.GetNodeList());
            }
            return ret;
        }
Missing Function
Note: This topice is missing code (PrintRecursive) that can be found in another related article:
http://msdn.microsoft.com/en-us/library/aa984381(VS.71).aspx