Search code examples
c#winformstreeviewtreenode

C# - Find a specific node or subnode of a treeview control


I have a problem with the TreeView control in WinForm. The thing is, I need to automate the process of inserting nodes by using a while loop and using the node previously inserted in the control as the parent node search criterion.

Here my problem arises, when I look for the node in the control I use this code:

foreach (TreeNode singleNode in Repository_TreeView.Nodes)
{
    if (singleNode.Text.Contains(specificPTN) == true)
    {
        Repository_TreeView.SelectedNode = singleNode;
    }

In this way, however, I only get the nodes in the highest level of the hierarchy. So, for example:

/--------------------------------------------------\
|    + rootnode1                                   |
|    |        +---> childnode1                     |
|    |                      +---> grandchildnode1  |
|    |                      |                      |
|    |                      +---> grandchildnode1  |
|    |                                             |
|    + rootnode2                                   |
|             +---> childnode2                     |
|                           +---> grandchildnode2  |
|                           |                      |
|                           +---> grandchildnode2  |
|                                                  |
|                                                  |
\--------------------------------------------------/

In this case my code would only get the node 'rootnode1' and 'rootnode2', when I need to get all the other subnodes instead.

I also tried using this lambda expression to look up the node by name:

TreeNode[] parentNodes = Repository_TreeView.Nodes
                                    .Cast<TreeNode>()
                                    .Where(r => r.Text == specificPTN)
                                    .ToArray();

The result, however, is always the same, 'rootnode1' and 'rootnode2' are always found.

I hope someone can help me find a way to get all the nodes and subnodes out of control. Thanks and sorry for the long explanation.


Solution

  • By iterating over TreeView->Nodes , you are getting only top level Nodes. TreeView->Nodes(of type TreeNodeCollection) has a Find(string, boolean) method that you can use to search for a node with specific text. You can call this method like

    Repository_TreeView.Nodes.Find(specificPTN, true) 
    

    to get all the matching nodes.