Masoud Masoud - 1 month ago 11
C# Question

gridview error: it results in a reentrant call to the SetCurrentCellAddressCore function

I have used below code for populating gridview with a customer object but i get error: Operation is not valid because it results in a reentrant call to the SetCurrentCellAddressCore function

List<Customer> customers=new List<Customer>();
customers.Add(customer);
DataTable dt = new DataTable();
DataColumn col0= new DataColumn("Customer Id",typeof(int));
DataColumn col1 = new DataColumn("Name", typeof(string));
DataColumn col2 = new DataColumn("Address", typeof(string));
DataColumn col3 = new DataColumn("City", typeof(string));
DataColumn col4 = new DataColumn("State", typeof(string));
DataColumn col5 = new DataColumn("ZipCode", typeof(string));
dt.Columns.Add(col0);
dt.Columns.Add(col1);
dt.Columns.Add(col2);
dt.Columns.Add(col3);
dt.Columns.Add(col4);
dt.Columns.Add(col5);
int i = 0;

foreach (Customer item in customers)
{
DataRow drow = dt.NewRow();
dt.Rows.Add(drow);
dt.Rows[i][col0] = Convert.ToInt32(item.CustomerID);
dt.Rows[i][col1] = item.Name.ToString();

dt.Rows[i][col2] = item.Address.ToString();
dt.Rows[i][col3] = item.City.ToString();
dt.Rows[i][col4] = item.State.ToString();
dt.Rows[i][col5] = item.ZipCode.ToString();
i++;
}

grvCustomer.Visible = true;

grvCustomer.DataSource = dt;

Answer

The exception is usually raised by the gridview in order to prevent an infinite loop from occurring. The cause of this is usually one of the following:

  • Changing the active cell while an operation is being performed on the currently-active cell

  • Beginning, ending or cancelling edit mode while a cell edit is already in-progress

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

Have a look at your handler for the CellValueChanged event and make sure you are not doing any of the above within the handler.

a quick workaround can be use the BeginInvoke. BeginInvoke is an asynchronous call, so gridview change/edit event returns immediately, and the method is executed after that, at that time gridview is no longer using the currently active cell.

this.BeginInvoke(new MethodInvoker(() =>
        {
            //do something
        }));
Comments