2011-07-06 32 views
2

我有這樣的代碼:通過獲取文件路徑排列TreeView?

public void AddNode(string Node) 
    { 
     try 
     { 
      treeView.Nodes.Add(Node); 
      treeView.Refresh(); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.ToString()); 
     } 
    } 

正如你看到的很簡單,這種方法獲取文件的路徑。像C:\Windows\notepad.exe

現在我想的TreeView控件來顯示它就像文件系統..

-C:\ 
    +Windows 

如果我點擊「+」它會是這樣的:

-C:\ 
    -Windows 
     notepad.exe 

這裏是我所得到的現在從發送這些方法到上面的方法:

TreeView current look

我該怎麼做,它會安排節點?

+0

#1我敢肯定你在你的例子中擁有這些電影吧? #2您是否將所有節點添加到根節點? #3 http://www.java2s.com/Code/CSharp/GUI-Windows-Form/TreeViewExample.htm –

回答

1

如果我是你,我會使用string.Split方法將輸入字符串拆分到子字符串中,然後搜索正確的節點以插入節點的相關部分。我的意思是,在添加節點之前,應該檢查節點C:\及其子節點(Windows)是否存在。

這裏是我的代碼:

... 
      AddString(@"C:\Windows\Notepad.exe"); 
      AddString(@"C:\Windows\TestFolder\test.exe"); 
      AddString(@"C:\Program Files"); 
      AddString(@"C:\Program Files\Microsoft"); 
      AddString(@"C:\test.exe"); 
... 

     private void AddString(string name) { 
      string[] names = name.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); 
      TreeNode node = null; 
      for(int i = 0; i < names.Length; i++) { 
       TreeNodeCollection nodes = node == null? treeView1.Nodes: node.Nodes; 
       node = FindNode(nodes, names[i]); 
       if(node == null) 
        node = nodes.Add(names[i]); 
      } 
     } 

     private TreeNode FindNode(TreeNodeCollection nodes, string p) { 
      for(int i = 0; i < nodes.Count; i++) 
       if(nodes[i].Text.ToLower(CultureInfo.CurrentCulture) == p.ToLower(CultureInfo.CurrentCulture)) 
        return nodes[i]; 
      return null; 
     } 
+0

嘿,謝謝! 我發現這些:http://stackoverflow.com/questions/1155977/populate-treeview-from-a-list-of-path http://stackoverflow.com/questions/673931/file-system-treeview/674119 #674119 但你給了我最好的答案! – Danpe

0

如果你在窗口形成(我猜是這樣),你可以實現IComparer類,並使用TreeView.TreeViewNodeSorter屬性:

public class NodeSorter : IComparer 
{ 
    // Compare the length of the strings, or the strings 
    // themselves, if they are the same length. 
    public int Compare(object x, object y) 
    { 
     TreeNode tx = x as TreeNode; 
     TreeNode ty = y as TreeNode; 

     // Compare the length of the strings, returning the difference. 
     if (tx.Text.Length != ty.Text.Length) 
      return tx.Text.Length - ty.Text.Length; 

     // If they are the same length, call Compare. 
     return string.Compare(tx.Text, ty.Text); 
    } 
} 
0

是,家長和孩子們沒問題區別?

樹中的每個節點也都有一個Nodes屬性,它表示其子節點的集合。您的AddNode例程需要進行更改,以便您可以指定要向其添加子節點的父節點。像:

TreeNode parent = //some node 
parent.Nodes.Add(newChildNode); 

如果你希望它只是填充路徑,並計算出父子關係本身,你將不得不寫一些代碼來解析路徑,並確定基於父節點路徑段。