2011-09-24 67 views
0

我有夫婦在樹視圖節點的列表,用戶可以拖動以創建子節點等C#獲取目錄使用TreeView節點信息

我使用一些方法來檢索父節點列表:

private static IList<Node> BuildParentNodeList(AdvTree treeView) 
    { 
     IList<Node> nodesWithChildren = new List<Node>(); 

     foreach (Node node in treeView.Nodes) 
      AddParentNodes(nodesWithChildren, node); 

     return nodesWithChildren; 
    } 

    private static void AddParentNodes(IList<Node> nodesWithChildren, Node parentNode) 
    { 
     if (parentNode.Nodes.Count > 0) 
     { 
      nodesWithChildren.Add(parentNode); 
      foreach (Node node in parentNode.Nodes) 

       AddParentNodes(nodesWithChildren, node); 
     } 
    } 

然後,父節點上我使用的擴展方法來獲得所有後代節點:

public static IEnumerable<Node> DescendantNodes(this Node input) 
{ 
     foreach (Node node in input.Nodes) 
     { 
      yield return node; 
      foreach (var subnode in node.DescendantNodes()) 
       yield return subnode; 
     } 
    } 

這裏是我的節點的典型佈置:

Computer 
    Drive F 
    Movies  
    Music 
     Enrique 
     Michael Jackson 
     Videos 

我需要具有子節點的每個節點的路徑的字符串表示形式。 E.g:

Computer\DriveF 
Computer\DriveF\Movies\ 
Computer\DriveF\Music\ 
Computer\DriveF\Music\Enrique 
Computer\DriveF\Music\Michael Jackson 
Computer\DriveF\Music\Michael Jackson\Videos 

我有問題得到這個確切的表示使用上述方法。任何幫助都感激不盡。謝謝。

+0

使用供應商的支持渠道尋求幫助這個非標準組件。 –

回答

1

這爲我工作:

private void button1_Click(object sender, EventArgs e) 
{ 
    List<string> listPath = new List<string>(); 
    GetAllPaths(treeView1.Nodes[0], listPath); 

    StringBuilder sb = new StringBuilder(); 
    foreach (string item in listPath) 
    sb.AppendLine(item); 

    MessageBox.Show(sb.ToString()); 
} 

private void GetAllPaths(TreeNode startNode, List<string> listPath) 
{ 
    listPath.Add(startNode.FullPath); 

    foreach (TreeNode tn in startNode.Nodes) 
    GetAllPaths(tn, listPath); 
} 
+1

**謝謝。有用。** – DelegateX