2016-06-14 4 views
2

мне нужно экспортировать структуру TreeView на закладку отформатированного текст, например, как это:C# WinForms - Отображение структура дерева в виде вкладок форматированного текста

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 

Может кто-нибудь, пожалуйста, помогите мне с этим? Большое спасибо!

+0

И это, как я вызываю его: TextTree = TreeViewSearch.ExportTreeNode (tvSearchResults.Nodes)) ; – user2430797

ответ

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"); 
+0

Спасибо. Это решило мою проблему. – user2430797

Смежные вопросы