DataGridView Delete Problem

I have a Datagridview control in a winForm application bound to a data adapter that references an Access 2007 table. The properties AlowUserToAddRows, AllowUserToDeleteRows, and MultiSelect are all set to True.  Everything works find except the following case:

If the user selects all the rows in the datagridview including the “*” row at the bottom of the datagridview and press the Delete key.  All the displayed records disappear and the “*” row is highlighted (selected).  Next the user clicks in the first column (or any column) of the “*” row and attempts to enter new data.  Upon depressing a keyboard key the message below appears.

    The following exception occurred in the DataGridView:

    System.IndexOutOfRangeException: Index 0 does not have a value. at
    System.Windows.Forms.CurrencyManager.get_Item(Int32 index) at
    System.Windows.Forms.DataGridView.DataGridViewDataConnection.GetError(int32 rowIndex)

    To replace this default dialog please handle the DataError event.

Note: Selecting all the rows except the “*” row at the bottom of the DataGridView works as expected.  Also, selecting only the “*” row while there are other rows in the DatGridView, and pressing the delete key and entering new data works just fine.  The error happens when all rows included the “*” rows are deleted and new data is entered.

Any ideas on how to fix this problem?
robtrueAsked:
Who is Participating?
 
rayraympCommented:
If I am correct, by "deleting" the "*" row, you would be throwing off the index of the table.  Try something like the following as a handle for something like "selectionChanged" or "multipleSelected" or an event such as that to lock the "*" cells (it can be modified to do a whole row):

If e.RowIndex < rowcount Then
DataGridView1.Item(e.ColumnIndex, e.RowIndex).ReadOnly = True
End If
0
 
robtrueAuthor Commented:
THANKS A MILLION!!!!  The “SelectionChanged” event did the trick.  Below is my code.  
 
With DataGridView1
        ' If all rows including the "*" row (for new record) are selected,
        ' then unselect the last row to prevent index out of range error.
        If .SelectedRows.Count = .RowCount Then .Rows(.RowCount - 1).Selected = False
End With
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.