0
votes

When I am trying to Delete all rows in DataGridView

I got this exception

Operation is not valid because it results in a reentrant call to the SetCurrentCellAddressCore Function

Notes :

I tryed this

datagridview1.Rows.Clear();

and this

foreach (DataGridViewRow item datagridview1.Rows)
{
    datagridview1.Rows.Remove(item);
}

and this

foreach (DataGridViewRow item datagridview1.Rows)
{
    datagridview1.Rows.RemoveAt(item.index);
}
2

2 Answers

0
votes

Clear the datasource that the DataGridView is bound to.

datasource.Clear()
0
votes

Try to call datagridview1.EndEdit(); before deleting rows.
See also: Why is my bound DataGridView throwing an “Operation not valid because it results in a reentrant call to the SetCurrentCellAddressCore function” error?

EDIT: Please note that you cannot delete rows in the following event handlers:

  • CellEnter
  • CellLeave
  • CellValidating
  • CellValidated
  • RowEnter
  • RowLeave
  • RowValidated
  • RowValidating

Source: MSDN