C# Treeview keys fullpath

2.7k views Asked by At

There is this treeview with nodes added like so:

tree.Nodes.Add("key", "DisplayText");
tree.Nodes["key"].Nodes.Add("key2", "DisplayText2);

I want to obtain the full path of the currently selected node, but I want the path of keys not the path of display text.

If the second node is selected, the tree.FullPath property will return the following:

"DisplayText\\DisplayText2"

But this is pointless to me, what I need is

"Key\\Key2"

What is the fastest way to acquire the full key path ?

3

There are 3 answers

0
rageit On BEST ANSWER

TreeNode.Name will give you the key values. There is no such property/method to return the path containing the key values. FullPath will give you path with display values. You can recurse to build the path with key values with something like this:

public string GetKeyPath(TreeNode node)
{
    if (node.Parent == null)
    {
        return node.Name;
    }

    return GetKeyPath(node.Parent) + "//" + node.Name;
}
0
dub stylee On

This is a pseudo-code rough idea.. not complete code, but just to give you an idea of where to start:

string ParentNodeName(TreeNode node)
{
    if (node.Parent == null)
    {
        return node.Name;
    }
    else
    {
        return ParentNodeName(node.Parent);
    }
}
0
A_V On

Since I needed an array anyway I figured I could make a function that receives a Treenode and returns an array of string containing the keys.

    private string[] FullKeyPath(TreeNode tn)
    {
        string[] path = new string[tn.Level + 1];
        for (int i = tn.Level; i >= 0; i--)
        {
            path[i] = tn.Name.ToString();
            if (tn.Parent != null)
            {
                tn = tn.Parent;
            }
        }
        return path;
    }