Sep 23, 2010

DataGridView Reentrant Error

The events on a datagridview seems to be unstable when there is a need to repopulate a datagridview within its events. It does makes sense as if you have a trigger on any change and to populate the grid, it can lead to an infinite loop. One of the errors I encountered was

System.InvalidOperationException was unhandled
Message="Operation is not valid because it results in a reentrant call to the SetCurrentCellAddressCore function."

In fact I had to repopulate the datagridview on CellEndEdit. I Googled a lot about it and found some solutions. I came up to something, which I am not sure is the most efficient one, but it works.

public delegate void InvokeDelegate();

private void datagrid_changed(object sender, EventArgs e)
    this.dataGridView.BeginInvoke(new InvokeDelegate(ModifyGrid));

private void ModifyGrid()
    // Method implemented to change datasource

Instead of modifying the datasource directly, I had to pass though a delegated called by BeginInvoke. It should work fine.

In WPF DataGrid it is as follows:

private void dataGridLines_RowEditEnding(object sender, EventArgs e)
    Dispatcher.BeginInvoke(new InvokeDelegate(InsertRow), null);


  1. Thank you so much for posting this. I had the same problem and this is the only thing that has worked for me.

  2. thks a lot ! version :

    Public Delegate Sub InvokeDelegate()

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    dgReassort.BeginInvoke(New InvokeDelegate(AddressOf Me.refreshDgReassort))
    End Sub

    Public Sub refreshDatagrid()
    datagrid.datasource = '...'
    End Sub

    This code allow you leave the cell while refreshing data