0

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);
}
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
Developer
  • 63
  • 6

2 Answers2

0

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

Community
  • 1
  • 1
Dmitry
  • 13,797
  • 6
  • 32
  • 48
  • Notes : my code is written into the event datagridView_CellEndEdit so i can't delete the row which contains the current cell – Developer Mar 17 '14 at 22:07
0

Clear the datasource that the DataGridView is bound to.

datasource.Clear()
Bazinga
  • 994
  • 4
  • 14
  • 42