C# DataGridView - Call sort from CellEndEdit event

2.1k Views Asked by At

At the moment I am using this.EndInvoke(this.BeginInvoke(new MethodInvoker( this.resortRows ))); to call the method that checks for empty cells and then sorts the DGV. But I am calling this from CellEndEdit.

Everything works fine if the event is called by pressing Enter or Tab, but If I click on another cell while still in EditMode I get an error on the line with the sort command:

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

This is the Sort command:

this.dataGridView1.Sort(this.dataGridView1.Columns[2], ListSortDirection.Ascending);

I tried to hande the MouseClick event like this:

private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
  this.dataGridView1.EndEdit();
}

But this works only if I click inside the DGV on the grey area (Not on any cell or header). How can I fix this?

1

There are 1 best solutions below

11
On BEST ANSWER

I actually tried your code and it seems that the problem is EndInvoke.
Just remove it (i.e. use only BeginInvoke) and it will work fine.

EDIT :

Using BeginInvoke without EndInvoke the invoked method will be executed just after CellEndEdit handler exits.

If you need to call a code after each sorting, just put it at the end of the invoked method.