santBart
santBart

Reputation: 2496

c# treeview path

I have TreeNode node.

something = treeview.Nodes[1].Nodes[4].Nodes[0]; 

TreeNode myNode = something;

And wish to know how pany parents it has and what indexes i need to use to find whole path out from this node.

I mean get "treeview.Nodes[1].Nodes[4].Nodes[0]" out from myNode

Upvotes: 0

Views: 2005

Answers (2)

Lukazoid
Lukazoid

Reputation: 19426

Something like this should work:

public IList<int> GetNodePathIndexes(TreeNode node)
{
    List<int> indexes = new List<int>();
    TreeNode currentNode = node;
    while (currentNode != null)
    {
        TreeNode parentNode = currentNode.Parent;
        if (parentNode != null)
            indexes.Add(parentNode.Nodes.IndexOf(currentNode));
        else
            indexes.Add(currentNode.TreeView.Nodes.IndexOf(currentNode));

        currentNode = parentNode;
    }
    indexes.Reverse();
    return indexes;
}

You can then look at the result of this to get the indexes, and the count, to get the number of parents.

IList<int> path = GetNodePathIndexes(myNode);

StringBuilder fullPath = new StringBuilder("treeview");
foreach (int index in path)
{
    fullPath.AppendFormat(".Nodes[{0}]", index);
}

Then fullPath.ToString() should return treeview.Nodes[1].Nodes[4].Nodes[0]

Upvotes: 1

DmitryG
DmitryG

Reputation: 17848

//...
string path = GetPath(treeView1.Nodes[0].Nodes[0].Nodes[1].Nodes[0]);
// now path is "treeView.Nodes[0].Nodes[0].Nodes[1].Nodes[0]"
//...
string GetPath(TreeNode node) {
    int index;
    Stack<string> stack = new Stack<string>();
    while(node != null) {
        if(node.Parent != null) {
            index = node.Parent.Nodes.IndexOf(node);
            stack.Push(string.Format("Nodes[{0}]", index));
        }
        else {
            index = node.TreeView.Nodes.IndexOf(node);
            stack.Push(string.Format("treeView.Nodes[{0}]", index));
        }
        node = node.Parent;
    }
    return string.Join(".", stack.ToArray());
}

Upvotes: 0

Related Questions