Caladan
Caladan

Reputation: 33

How to find the index of a root folder in a treeview?

How to find the index of every root folder in a treeview? Let's say there's a treeview with 4 root nodes. They're all on the same level and all of them have child nodes (not displayed):

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

Now let's suppose there's a selected node on the branch of the "c" root node. How could I get the index of the "c" node? (In this case, it's the third one between root nodes).

So, given a selected node, how could I get the index of its root node?

Upvotes: 0

Views: 943

Answers (1)

Nino
Nino

Reputation: 7095

To achieve your task, you should find clicked node's parent and then parent's parent etc... So, we need a recursion here.

Take a look at sample code (with comments):

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

Upvotes: 1

Related Questions