I seem to always come into contact with these "We hate you!" type errors, and this one is up there. Took me a while to figure this out, Humor me.
Open up a new web project, create a short number of nodes as such...(sorry its in VB)
Dim Master As New TreeNode("Master", "1m")
Dim Node1 As New TreeNode("Item1", "1p")
Dim Node2 As New TreeNode("Item2", "2p")
Dim Child As New TreeNode("Child1", "1c")
'add child node to node1
Node1.ChildNodes.Add(Child)
'add node1 and 2 to Master
Master.ChildNodes.Add(Node1)
Master.ChildNodes.Add(Node2)
Ok, got that? Now if you tag this into a treeview, you get this kind of display...
Master
- Item1
o Child1
- Node2
Which is great, but what if you wanted a tree of JUST the children items to Master? so it would look like this...
Item1
- Child1
Item2
How would you do that? Use some kind of loop? How about trying TreeView1.Nodes.Add(Master.ChildNodes) (bernt, one's a collection and the control only expects a single node)? I decided to use the Master.ChildNodes and try a foreach loop -- surprise, and recieved this error.
Index was out of range. Must be non-negative and less than the size of the collection.
Hu? My code isn't complicated, so what'd I do wrong? I move out my Master.ChildNodes into its own collection, "nodes", slightly refactor and check my logic.
For count As Integer = 0 To nodes.Count - 1
Me.treeView.Nodes.Add(nodes(count))
Next
yep, I'm starting at 0, minus one off the collection count -- thats lining up, makes sense so I run the code, check the count, yep its 2, thats good
I'm thinking at this point maybe I'm counting wrong, maybe it IS 1 based, so I step into the next and see this
Wait ...hu? Why would it REMOVE an item from my collection when I add it to the treeview? What if I wanted that for multiple places? This doesn't add up. So, let me ask the question -- WHY is it doing this?! If you switch the Me.treeView.Nodes.Add(nodes(0)) it'll build just fine. I just don't get it. With other things like lists and the like, you can rip though those things and pull only what you need into whatever and it does not remove stuff.
Can someone try this and see if you get the same thing?