开发者

add a node to specific child node

I can add a node to a treeview add method.But I want to add 开发者_如何学Ca 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.


TreeNode[] tn = treeView.Nodes[0].Nodes.Find(search.Text, true);
if (tn.Count>0) 
   tn[0].Nodes.Add(node);
else
   //handle node not found


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"));


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;
}


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜