问题
I can add a node to a treeview add method.But I want to add a node to specific child node. For example want to add a node to node5
|___node0
|___node1
| |___node3
| |___node4
| |___node5
|___node2
How do I can do this? Thanks.
回答1:
Basic recursive tree node searcher, of the top of my head. If you only need to search by key, the answer by weismat is the easiest, however if you need to search by the data on the nodes, you should consider this solution as you can replace the name search with whatever you might like to find.
private TreeNode FindNode(TreeNode root, String name)
{
foreach (TreeNode node in root.Nodes)
{
if (node.Nodes.Count > 0)
return FindNode(root, name);
if (node.Name == name)
return node;
}
return null;
}
回答2:
TreeNode[] tn = treeView.Nodes[0].Nodes.Find(search.Text, true);
if (tn.Count>0)
tn[0].Nodes.Add(node);
else
//handle node not found
回答3:
If you have the child node reference , you can simply access its Nodes Collection and add new child into its collection as shown below
node5.Nodes.Add(New TreeNode("temp"));
回答4:
William was right, but the method should look like this:
private TreeNode FindNode(TreeNode root, String name)
{
foreach (TreeNode node in root.Nodes)
{
if (node.Name == name)
return node;
else
{
if (node.Nodes.Count > 0)
return FindNode(node, name);
}
}
return null;
}
tested this and works just fine,
Cheers!
来源:https://stackoverflow.com/questions/4384818/add-a-node-to-specific-child-node