Search code examples
c#winformsrecursiontreeviewtext-formatting

c# winforms - Display tree structure as tab formatted text


I need to export a treeView structure to a tab-formatted-text such as this:

node 1
   child node 1.1
      child node 1.1.1
         child node 1.1.1.1
node 2
   child node 2.1
      child node 2.1.1
         child node 2.1.1.1
...etc

I created the following recursive routine:

     public static string ExportTreeNode(TreeNodeCollection treeNodes)
     {
        string retText = null;

        if (treeNodes.Count == 0) return null;

        foreach (TreeNode node in treeNodes)
        {
            retText += node.Text + "\n";

            // Recursively check the children of each node in the nodes collection.
            retText += "\t" + ExportTreeNode(node.Nodes);
        }
        return retText;
    }

Hoping that it will do the job, but it doesn't. Instead, it outputs the tree structure as:

node 1
   child node 1.1
   child node 1.1.1
   child node 1.1.1.1
   node 2
   child node 2.1
   child node 2.1.1
   child node 2.1.1.1

Can someone please help me with this? Many thanks!


Solution

  • The assumption you make on this line is incorrect: It only indents the first child node.

    retText += "\t" + ExportTreeNode(node.Nodes);
    

    Also, your tabs are not aggregating - There will effectively never be more than one tab to the left. Add an indent parameter to your function:

    public static string ExportTreeNode(TreeNodeCollection treeNodes, string indent = "")
    

    and change

    retText += node.Text + "\n";
    
    // Recursively check the children of each node in the nodes collection.
    retText += "\t" + ExportTreeNode(node.Nodes);
    

    to

    retText += indent + node.Text + "\n";
    
    // Recursively check the children of each node in the nodes collection.
    retText += ExportTreeNode(node.Nodes, indent + "\t");