user3818167
user3818167

Reputation: 13

C#, can`t find TreeView child node by text

i have the following code to find a child node in TreeView:

public void NodeHinzufuegen()
{
    // Other stuff above
    ReturnCompleteFolderPath(erstellterPunkt.Text);
    // Other stuff below
}



public void ReturnCompleteFolderPath(string nodename)
{
    TreeNode[] tempnode = tree_vorlagen.Nodes.Find(nodename, true);
        if (tempnode.Length > 0)
        {
            //tree_vorlagen.SelectedNode = tempnode[0];
            MessageBox.Show(tempnode[0].Parent.Name);
        }
}

So ReturnCompleteFolderPath() is called and succesfully transmits the text to ReturnCompleteFolderPath (checked by mouseover in debug). If I mouseover tempnode in debug mode it says {System.Windows.Forms.TreeNode[0]} and if i mouseover tempnode.Length it says "0". So it seems the node couldn`t be found. Any ideas about this?

My Treeview looks like this.

Test1

"Test2" is the text transmitted to ReturnCompleteFolderPath function.

Upvotes: 1

Views: 2735

Answers (2)

Thanatos
Thanatos

Reputation: 136

From the TreeNodeCollection.Find documentation:

Finds the tree nodes with specified key, optionally searching subnodes.

...

The Name property corresponds to the key for a TreeNode in the TreeNodeCollection.

Unless you're setting up a Name for your TreeNodes, this method will never find results. If you want to search by text, you could attach the names when the nodes are created

    TreeNode test2 = new TreeNode("Test2") { Name = "Test2" };

or even add names to all of them:

    // Fetch each node without a name and give it one
    foreach (TreeNode node in tree_vorlagen.Nodes.Find("", true))
        node.Name = node.Text;

    // Now the "Test2" node can be found
    Console.WriteLine(tree_vorlagen.Nodes.Find("Test2", true).Length); // Prints 1

Upvotes: 2

Chris
Chris

Reputation: 5514

The TreeNodeCollection.Find method finds nodes where the Name property matches the search string, i.e. not the Text. So I'd guess that's why it's not returning anything (seeing how I didn't know that myself until just now either)!

So either make sure you set the name too, or whip up your own search function to find it.

More information here

Upvotes: 0

Related Questions