ziorrinfotech
asked on
getting Index was out of range. error while running a loop for treenode collection
I have saved my tree nodes collection in a session object and, i am using that collection to load the tree again.
I am running the below code to add nodes into the tree view control
but i am getting this error when i run this code.
Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index
when i did some testing then i found out the when the nodes are added to the tree view then "nodes.count" is decreasing by1.
and this error comes when the loops run half +1 time of nodes.count.
any one could help me out here.
I am running the below code to add nodes into the tree view control
but i am getting this error when i run this code.
Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index
when i did some testing then i found out the when the nodes are added to the tree view then "nodes.count" is decreasing by1.
and this error comes when the loops run half +1 time of nodes.count.
any one could help me out here.
TreeNodeCollection nodes = _defaultPageViewState.Nodes;
if (nodes == null) { return; }
for (int i = 0; i <= nodes.Count; i++) {
ParentTreeView.Nodes.Add(nodes[i]);
}
Sorry, the last code snippet should be like this
TreeNodeCollection nodes = _defaultPageViewState.Nodes;
if (nodes == null) { return; }
for (int i = 0; i < nodes.Count; i++) {
ParentTreeView.Nodes.Add(nodes[i]);
}
Yep you need the "-1" after the count in the for loop.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Sorry but change the line inside foreach to this one
ParentTreeView.Nodes.Add(node);
Open in new window