2017-04-27 67 views
0

如何查找樹視圖中每個根文件夾的索引? 假設有一個包含4個根節點的樹形視圖。他們都在同一水平上,他們都具有子節點(不顯示):如何查找樹視圖中根文件夾的索引?

|-a 
|-b 
|-c 
|-d 

現在讓我們假設有一個在「C」根節點的分支選擇的節點。我怎麼能得到「C」節點的索引? (在這種情況下,它是根節點之間的第三個節點)。

因此,給定一個選定的節點,我怎麼能得到它的根節點的索引?

+0

的WinForms? WPF? asp.net mvc? – Backs

+0

WinForms。問題是我填充了根目錄文件夾列表樹視圖,然後他們的子文件夾被添加爲子節點。但只有他們的名字存儲在treeview中。 我必須重建從選定節點的完整路徑。所以,我必須將正確的根文件夾添加到選定節點的完整路徑以創建完整路徑。這就是爲什麼我必須知道每個根節點的索引,才能將它們與列表中的相應根文件夾配對。 – Caladan

+0

分享你迄今爲止所做的工作。 –

回答

1

要實現你的任務,你應該找到點擊節點的父節點,然後是父節點的父節點等......所以,我們需要在這裏遞歸。

看看示例代碼(帶註釋):

private void Form1_Load(object sender, EventArgs e) 
{ 
    //add test data on form load (you can do it on form design, too. 
    //there are 4 root nodes and each of them has one subnode. 
    //Additionally, c's first node, called 'c-1', has it's own child. 
    treeView1.Nodes.Add(new TreeNode("a")); 
    treeView1.Nodes.Add(new TreeNode("b")); 
    treeView1.Nodes.Add(new TreeNode("c")); 
    treeView1.Nodes.Add(new TreeNode("d")); 
    treeView1.Nodes[0].Nodes.Add(new TreeNode("a-1")); 
    treeView1.Nodes[1].Nodes.Add(new TreeNode("b-1")); 
    treeView1.Nodes[2].Nodes.Add(new TreeNode("c-1")); 
    treeView1.Nodes[3].Nodes.Add(new TreeNode("d-1")); 
    treeView1.Nodes[2].Nodes[0].Nodes.Add(new TreeNode("c-1-1")); 

    //expand those nodes to see things clearly 
    treeView1.ExpandAll(); 

    //subscribe to after select event. When user selects one node, treeView1_AfterSelect method will be called. 
    //this can be done on form designer too, on properties panel 
    treeView1.AfterSelect += treeView1_AfterSelect; 

} 

private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) 
{ 
    //this method will be called when you select node 
    //find topmost parent by calling method FindTopMostParent and passing it selected node 
    var topmostParent = FindTopMostParent(e.Node); 

    //here's your index of topmost node (parent or grandparent or grand-grand of selcted node(
    var index = treeView1.Nodes.IndexOf(topmostParent); 

} 

private TreeNode FindTopMostParent(TreeNode node) 
{ 
    //first, we check if passed node has parent. If not, return that node, because it's the topmost one 
    //then, repeat that search for parent again and again until you find that node which does not have parent 
    while (node.Parent != null) 
     return FindTopMostParent(node.Parent); 

    //return parentless node :) 
    return node; 
} 
+0

謝謝,這是我想要的。 – Caladan