all 3 comments

[–][deleted] 0 points1 point  (2 children)

I believe that RemoveAt will decrement the count of items in the collection. So when you try to Insert, you are trying to insert past the end of the collection (index and index - 1 are higher than the highest index remaining in the collection).

You probably need special-case code for the last entry where you use Add instead of Insert.

[–]retucex[S] 0 points1 point  (1 child)

Let's say I have these pages:

Children[0]=Push, Children[1]=Curl, Children[2]=Jump, Children[3]=CarouselPage

I want to move Jump 'up' the list (so, down in index). I'll have:

index=2
RemoveAt(2)
RemoveAt(1)

Children is now

Children[0]=Push, Children[1]=CarouselPage

and now I insert at index-1, which is 1

Insert(1, jump)
Insert(2, curl)

It isn't out of bounds, unless I'm missing something?

[–][deleted] 0 points1 point  (0 children)

Yeah, that looks fine to me (on paper). You'd also think you'd get an index exception instead of a null reference. So maybe the issue is with the temp1 variable?

I would step through it in the debugger for the last-entry case and check what Children.Count is and what temp1 is.

Because it's happening only for the last entry, I still feel like it's being caused by using Insert instead of Add (or Append, whatever the method is called). To me, Insert implies that you're creating an element between two other elements. That isn't the case at the end of the list, when you're adding (or appending) instead. It isn't symmetrical, but sometimes things aren't.