Showing posts with label DatagridView. Show all posts
Showing posts with label DatagridView. Show all posts

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