0

I have a TreeView in my code (Tree1) and i am going to add nodes in depth , using my CreatTree() method. In Debug i understood that this line

(Tree1.Nodes[i].ChildNodes.Add(new TreeNode(i.ToString()))) does not lead to adding a node to Tree so the error in the loop is:

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

Can anybody tell me how can i add a Child to a certain Node?

<asp:TreeView ID="Tree1" runat="server"  >  
</asp:TreeView>

The code behind is:

protected void CreateTree( )
        {

            Tree1.Nodes.Add(new TreeNode("0"));


            for (int i = 0; i < 4; i++)
                Tree1.Nodes[i].ChildNodes.Add(new TreeNode(i.ToString()));;



        }
Sal-laS
  • 11,016
  • 25
  • 99
  • 169

2 Answers2

0

can you tried with below code because at patent level you have added only 1 record and you tried to add new child node at four different parent node.

protected void CreateTree( )
        {

            Tree1.Nodes.Add(new TreeNode("0"));


            for (int i = 0; i < 4; i++)
                Tree1.Nodes[0].ChildNodes.Add(new TreeNode(i.ToString()));;



        }
Naresh Pansuriya
  • 2,027
  • 12
  • 15
0

This should do what I think you're looking for:

protected void CreateTree()
{
    Tree1.Nodes.Add(new TreeNode("0"));

    TreeNode currentNode = Tree1.Nodes[0];

    for (int i = 0; i < 4; i++)
    {
        currentNode.ChildNodes.Add(new TreeNode(i.ToString()));
        currentNode = currentNode.ChildNodes[0];
    }
}

You'll end up with 5 nodes, one under each other.

Damon
  • 3,004
  • 7
  • 24
  • 28