4227

c# datagridview index -1 does not have a value

Question:

I have a strange exception. Sometimes - not all the times, when clicking a datagridview, I get this exception:

System.IndexOutOfRangeException: Index -1 does not have a value. at System.Windows.Forms.CurrencyManager.get_Item(Int32 index) 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.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr l param)

The grid is re populated automatically from a List.

When debugging (using vs 2013 debug mode), the exception isn't being caught- perhaps because it happens in a differed thread? I've seen it happens to others, but I can't trace it in my case, because it doesn't always happens.

Any ideas about this would be highly appreciated, thanks

EDIT:

The answer below is generaly currect, but in my specific case, I just needed to do datagridview.refresh() before clicking on it.

Answer1:

Make sure that the maximum index on a list is less than the list size The maximum index on a list must be less than the list size. For more information, see <a href="http://msdn.microsoft.com/en-US/library/45b76eb2(v=vs.80).aspx" rel="nofollow">Arrays in the Common Type System</a>

Make sure the index is not a negative number. This exception will be thrown if the index is less than zero.

Make sure data column names are correct. This exception may be thrown if the data column name being supplied to the <a href="http://msdn.microsoft.com/en-US/library/system.data.dataview.sort(v=vs.80).aspx" rel="nofollow">System.Data.DataView.Sort</a> property is not valid. For more information, see the <a href="http://msdn.microsoft.com/en-US/library/system.data.dataview(v=vs.80).aspx" rel="nofollow">DataView</a> class.

Recommend