[Solved] System.ArgumentOutOfRangeException Toolstrip menu


Although this question is downvoted for good reasons, it’s the only hit I got while googling for “xLayoutRow ArgumentOutOfRangeException”, so I’ll still share my experiences here.

I encountered an exception with the top part of the stack trace in this post:

System.ArgumentOutOfRangeException - Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
at System.Collections.ArrayList.get_Item(Int32 index)
at System.Windows.Forms.Layout.ArrangedElementCollection.get_Item(Int32 index)
at System.Windows.Forms.Layout.FlowLayout.xLayoutRow(ContainerProxy containerProxy, ElementProxy elementProxy, Int32 startIndex, Int32 endIndex, Rectangle rowBounds, Int32& breakIndex, Boolean measureOnly)
at System.Windows.Forms.Layout.FlowLayout.xLayout(IArrangedElement container, Rectangle displayRect, Boolean measureOnly)
at System.Windows.Forms.Layout.FlowLayout.GetPreferredSize(IArrangedElement container, Size proposedConstraints)

In my case the cause was, summarized:

  • A UserControl of type MyControl contains a FlowLayoutPanel.
  • Instance a of MyControl is instantiated and added to the Controls collection of a container control b: b.Controls.Add(a)
  • During this Add operation, through events triggering other events, all controls in b.Controls are disposed, including a.
  • The exception followed from the call b.Controls.Add(a) which was still unfinished.

Of course disposing the control while adding it to the controls collection was not my intention and finding the cause allowed me to solve the problem immediately. What seemed to happen was that the FlowLayoutPanel tries to do its layout, but it and its controls are being removed and disposed in-flight, which understandably makes it fail.

Maybe this helps the OP or someone else who encounters this exception.

1

solved System.ArgumentOutOfRangeException Toolstrip menu