How to avoid calling setCurrentCellAddressCore again?

I have a function called from cell_endit. It moves the dataGridViewRow inside the dataGridView:

private void moveRowTo(DataGridView table, int oldIndex, int newIndex) { if (newIndex < oldIndex) { oldIndex += 1; } else if (newIndex == oldIndex) { return; } table.Rows.Insert(newIndex, 1); DataGridViewRow row = table.Rows[newIndex]; DataGridViewCell cell0 = table.Rows[oldIndex].Cells[0]; DataGridViewCell cell1 = table.Rows[oldIndex].Cells[1]; row.Cells[0].Value = cell0.Value; row.Cells[1].Value = cell1.Value; table.Rows[oldIndex].Visible = false; table.Rows.RemoveAt(oldIndex); table.Rows[oldIndex].Selected = false; table.Rows[newIndex].Selected = true; } 

in the row table. Rows.Insert (newIndex, 1) I get the following error:

Unhandled exception of type "System.InvalidOperationException" in System.Windows.Forms.dll

Additional data: the operation is invalid because it leads to a repeated call to the SetCurrentCellAddressCore function.

This happens when I click on another cell while editing the current cell. How do I avoid such an error and did I insert my line correctly?

+5
source share
2 answers

This error is caused by

Any operation that changes the active cell when the DataGridView is still using it

Like the accepted answer in this post .

Bugfix (I checked): use BeginInvoke to call moveRowTo .

 private void dataGridView2_CellEndEdit(object sender, DataGridViewCellEventArgs e) { this.BeginInvoke(new MethodInvoker(() => { moveRowTo(dataGridView2, 0, 1); })); } 

BeginInvoke is an asynchronous call, so dataGridView2_CellEndEdit returns immediately, and then dataGridView2 is moveRowTo , then dataGridView2 no longer uses the current active cell.

+16
source
 if ( (datagridview.SelectedCells[0].RowIndex != datagridview.CurrentCell.RowIndex) || (datagridview.SelectedCells[0].ColumnIndex!= datagridview.CurrentCell.ColumnIndex) ) { return; } 
-1
source

Source: https://habr.com/ru/post/1205333/


All Articles