views:

191

answers:

5

hI,

I am working with a treeview in C# using visual studio 2005 and want to find a tree node and add nodes below it upon a button being pressed in my windows forms application. I have tried using treeView1.Nodes.Find("My_Text", true); where "My_Text" is the text associated with the node under which i want to add mode nodes.

However I cannot find a way to use this to my advantage as I dont know what this statement returns.

I ntend to use treeView1.SelectedNode.Nodes.Add(newnode); to add nodes but for that I need to select a node first. And treeView1.Nodes.Find does not look likt it selects the node for me. Any help?

+1  A: 

Do you need to use SelectedNode.Nodes.Add()? The Nodes.Add(...) operation can be performed on any TreeNode. So, if you can find the node at all, simply call node.Nodes.Add(..). You don't need to select it first.

Have a look at the documentation or intellisense information to see what the Find() method returns.

John Fisher
A: 

TreeView.Nodes.Find returns an array of nodes that match the string you specified. You can then use the Add method on the nodes to add sub-nodes, obviously if you have more than 1 node in the array then you have a non-unique situation so if you were looking for a specific node you'd need more information on which to identify it.

Lazarus
+1  A: 

Are you sure that a node with give text exists in your application? I just tried a simple test application and the Find method worked without problems...

    private void button1_Click(object sender, EventArgs e) {
        // WARNING: add checks
        TreeNode[] nodes = treeView1.Nodes.Find("Node2",true);
        TreeNode node = nodes[0];
        node.Nodes.Add("child node");
    }
Paolo Tedesco
thanks..works perfectly now.
VP
+1  A: 

treeView1.Nodes.Find() returns an array of TreeNode objects. If you are sure there is one and only one such node, you can do this:

 var node = treeView1.Nodes.Find("My_Text", true)[0];
 node.Nodes.Add(newnode);

If there can be more than one such node, you need some other way to disambiguate first. And if there can be no such node, you need to add some error checking in there as well.

Martinho Fernandes
A: 

Here's an article that describes adding nodes to a TreeView:

Working with TreeView Controls

Jay Riggs