I had encountered a strange error in my winforms .NET application, when I entered a form and clicked a GridView bound to a IList<T> collection:
System.IndexOutOfRangeException: Index -1 does not have a value.
at System.Windows.Forms.CurrencyManager.get_Item(Int32 index)
at System.Windows.Forms.CurrencyManager.get_Current()
at System.Windows.Forms.DataGridView.DataGridViewDataConnection.OnRowEnter(DataGridViewCellEventArgs e)
at System.Windows.Forms.DataGridView.OnRowEnter(DataGridViewCell& dataGridViewCell, Int32 columnIndex, Int32 rowIndex, Boolean canCreateNewRow, Boolean validationFailureOccurred)
at System.Windows.Forms.DataGridView.SetCurrentCellAddressCore(Int32 columnIndex, Int32 rowIndex, Boolean setAnchorCellAddress, Boolean validateCurrentCell, Boolean throughMouseClick)
at System.Windows.Forms.DataGridView.OnCellMouseDown(HitTestInfo hti, Boolean isShiftDown, Boolean isControlDown)
at System.Windows.Forms.DataGridView.OnCellMouseDown(DataGridViewCellMouseEventArgs e)
at System.Windows.Forms.DataGridView.OnMouseDown(MouseEventArgs e)
at System.Windows.Forms.Control.WmMouseDown(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.DataGridView.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
Apparently when a datasource collection haven’t changed since binding the error would not occur (or I have clicked a row with object existing in the collection before the bind). Someone wrote that this is caused by IList<T> not supporting change notification. Strange explanation, GridView shows up all elements correctly, but is stupid enough to tell that ther is no element at index -1 when you click it!
Anyway the solution is simple, rebind the GridView.
A similar problem in different circumstances:
http://groups.google.com/group/microsoft.public.dotnet.vb.general/msg/6d15a3fb83c78872?as_umsgid=1163194852.922541.167120@f16g2000cwb.googlegroups.com