C# DataGridView - deleting a row from the underlying BindingList (user highlights row and presses Del) and refreshing the grid removes the next row from the view.
I am using the UserDeletingRow event to remove the item from my underlying BindingList. I then either grd.Refersh() or I re-query the database and rebind the grid to the BindingList, however the view takes out the next row in both cases. When I debug, the row is still in my BindingList. I need to press my Search Button again (which my own re-query procedure calls) to get all the data to show.
This was the result of many efforts and searching many articles which said I should rebind my grid to the datasource.
If I take the Refersh or re-query out of the user deleting event and put it in UserDeletedRow, I get the "Index x does not have a Value" error. I also get this error if I add an EndEdit call.
I don't want to have to add a Delete button but would prefer the user to delete the row by selecting the whole row and pressing delete.
Code:
private void grdRequests_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
if (e.Row.Index == -1) return;
Request r = (Request)e.Row.DataBoundItem;
if (r.RequestID != null && r.RequestID != 0)
{
Cursor.Current = Cursors.WaitCursor;
if (r.Approved)
{
MessageBox.Show("You may not delete this Request, it has been approved", "Delete Request", MessageBoxButtons.OK, MessageBoxIcon.Hand);
e.Cancel = true;
return;
}
try
{
DataController.DeleteRequest((int)r.RequestID);
GridRequestsData.RemoveAt(e.Row.Index);
}
catch (Exception ex)
{
MessageBox.Show("Unexpected error deleteing request : " + ex.Message);
e.Cancel = true;
}
Cursor.Current = Cursors.Default;
}
else
{
//not in the database, just remove the row
if (!grdRequests.CurrentRow.IsNewRow)
{
GridRequestsData.RemoveAt(e.Row.Index);
}
}
RefreshGridDataSource();
//grdRequests.Refresh();
}