The .NET TreeView control does not provide any method to get a TreeNode if you have its full path. The TreeNode has a FullPath property that returns the Full Path of the specified node. But there is no way to get a node in the TreeView, by specifying its path.
In most of the online resources, blogs and forums, I have seen programmers achieving the target using recursive functions. But I find recursive functions hard to debug besides other problems and always avoid them if possible. Moreover, the recursive methods may be good for searches once in a while, but not otherwise.
Setting up a way to specify FullPath to get the appropriate node is easy. The TreeNode already has a Find method. All we need is some way to use the method for our needs.
I will demonstrate the concept here using Extension Methods for easiness. But just in case you are using .NET framework 2.0 (Visual Studio 2005) or lower, you can make appropriate changes to use them as normal functions, since extension methods are not supported on them. You just need to remove the <Extension()> _ part from the function declarations.
Now when you want to add a new TreeNode, use the new AddTreeNode method instead of the normal Nodes.Add() way. Nodes added in this manner save their key information too along with them, which helps us get the node by Full Path later whenever we need to.
For a demo on using these methods, start a new VB.NET Windows Forms application.
On the form, add a TreeView control and two Button controls.
Add the following code:
Run the code.
First click Button1. This will add a few nodes for demo. Then click Button2. The node "NodeA\NodeB\NodeC" should be selected and shown in the Message Box too. Change this path to something else. Then run again and see if it still works correctly.
How the Code Works
The TreeNode already has a Find method, which accepts a key (Name) and returns the node with specified key. So all we do is, while creating the TreeNodes, we save the key (Name) along with the Text. This later helps us find the node when we specify it the Full Path.