2014-10-23 32 views
5

Tôi có một chức năng được gọi từ cell_endedit. Nó di chuyển một dataGridViewRow bên trong một DataGridView:Làm thế nào để tránh cuộc gọi reentrant đến setCurrentCellAddressCore?

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; 
} 

tại table.Rows.Insert hàng (newIndex, 1) tôi nhận được lỗi sau:

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

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

Nó xảy ra khi tôi bấm vào ô khác trong quá trình chỉnh sửa ô hiện tại. Làm cách nào để tránh lỗi như vậy và chèn hàng của tôi chính xác?

Trả lời

15

Lỗi này là do

Any operation that results in the active cell being changed while the DataGridView is still using it

Khi trả lời chấp nhận in this post.

Sửa chữa (Tôi đã xác minh): sử dụng BeginInvoke để gọi moveRowTo.

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

BeginInvoke là một cuộc gọi không đồng bộ, vì vậy dataGridView2_CellEndEdit lợi nhuận ngay lập tức, và các phương pháp moveRowTo được thực hiện sau đó, tại thời điểm đó dataGridView2 không còn được sử dụng các tế bào đang hoạt động.

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

Trong khi mã này có thể trả lời câu hỏi, cung cấp thêm ngữ cảnh về cách thức và/hoặc lý do giải quyết vấn đề sẽ cải thiện giá trị lâu dài của câu trả lời. –

Các vấn đề liên quan