0

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.

2 Answers 2

1

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 Arrays in the Common Type System

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 System.Data.DataView.Sort property is not valid. For more information, see the DataView class.

1

I had the same problem. The issue was the DataGridView refresh.

before was like this:

myGrid.DataSource = null;
myGrid.DataSource = myList;

I have resolved with this trick:

myGrid.DataSource = null;
if (myList.Count > 0)
  myGrid.DataSource = myList;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.