Reputation: 372
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 ?
Upvotes: 1
Views: 2852
Reputation: 372
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;
}
Upvotes: 1
Reputation: 3601
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;
}
Upvotes: 2
Reputation: 3342
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);
}
}
Upvotes: 1