如何在树视图中查找根文件夹的索引?

时间:2017-04-27 02:45:04

标签: c#

如何在树视图中查找每个根文件夹的索引? 假设有一个包含4个根节点的树视图。它们都处于同一级别,并且所有子节点都有子节点(未显示):

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

现在让我们假设在“c”根节点的分支上有一个选定的节点。我怎么能得到“c”节点的索引? (在这种情况下,它是根节点之间的第三个)。

因此,给定一个选定的节点,我怎样才能获得其根节点的索引?

1 个答案:

答案 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;
}