gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:48:43 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com