c# winforms - 将树结构显示为制表符格式的文本

标签 c# winforms recursion treeview text-formatting

我需要将 treeView 结构导出为制表符格式的文本,如下所示:

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

我创建了以下递归例程:

     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;
    }

希望它能完成工作,但事实并非如此。相反,它将树结构输出为:

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

有人可以帮我解决这个问题吗?非常感谢!

最佳答案

您在这一行所做的假设是不正确的:它只缩进了第一个子节点。

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

此外,您的选项卡没有聚合 - 实际上左侧的选项卡永远不会超过一个。向您的函数添加一个缩进参数:

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

和改变

retText += node.Text + "\n";

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

retText += indent + node.Text + "\n";

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

关于c# winforms - 将树结构显示为制表符格式的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37803997/

相关文章:

c# - 如何在不序列化的情况下执行 ActivityBuilder?

c# - C# 6 字符串插值的默认区域性是什么?

vb.net - 尝试删除以前在 Visual Basic 中创建的边框

c# - 在 instagram 中获取用户 ID

java - 糟糕的动态编程实现或 HashMap 慢?

c - 仅打印那些总和为 10 的 3 位数组 - C 程序

C#:在文本文件中混淆密码的最佳实践?

c# - 如何创建一个包含每个单词(通配符)的短语列表?

c# - 根据当前鼠标位置缩放图形

django:使用保存后信号进行递归