ILovephp123 ILovephp123 - 3 months ago 23
C# Question

Select root node by text and add child

I want to add a child node to a root node.

The root node's text is "Hello".

How can I go about adding "hi" as a child node, to the root node, "Hello"

I tried this

databaseInfoTreeView.SelectedNode = "Hello";
databaseInfoTreeView.SelectedNode.Nodes.Add("Hi");


But I get the error


Cannot implicitly convert type 'string' to
'System.Windows.Forms.TreeNode'


On this line
databaseInfoTreeView.SelectedNode = "Hello";


Why doesn't it work, and how do I do this correctly?

enter image description here

Answer

You can't select tree nodes using a text. You need to get a reference for the "Hello" node some other way. You could:

1) Get the reference when you create the node and then add a child:

var root = databaseInfoTreeView.Nodes.Add("Hello");
root.Nodes.Add("Hi");

// Then if you want you can even set it as the current selected node
databaseInfoTreeView.SelectedNode = root;

2) Get the reference directly from the node index:

var root = databaseInfoTreeView.Nodes[0];
root.Nodes.Add("Hi");

3) Manually select the node on the treeview control, on you user interface and then add a node programatically:

if (databaseInfoTreeView.SelectedNode != null)
    databaseInfoTreeView.Nodes.Add("Hi");

Hope that helps...