【问题标题】:c# winforms - Display tree structure as tab formatted textc# winforms - 将树结构显示为制表符格式的文本
【发布时间】:2016-10-14 17:06:33
【问题描述】:

我需要将 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

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

【问题讨论】:

  • 这就是我调用它的方式:textTree = TreeViewSearch.ExportTreeNode(tvSearchResults.Nodes));

标签: c# winforms recursion treeview text-formatting


【解决方案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");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 2013-04-09
    相关资源
    最近更新 更多