数据网格视图CellValueChanged事件抛出InvalidOperationException

Ank*_*uhe 6 .net c# datagridview invalidoperationexception winforms

InvalidOperationException在我的更新改变单元格的值,并直接点击菜单条项开放新的Winform.

   private void dgv_category_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            DataTable dt = new DataTable();
            dt = u.operationOnDataBase(sqlquery_selectCategory, 3);
            if (dt.Rows.Count > 0)
            {
                MessageBox.Show("Category Already Exist...");

            }
            else
            {
                u.operationOnDataBase(sqlquery_UpdateCategory, 1);
                u.SyncMaster("update", "CategoryDetails", 0, Convert.ToInt32(dgv_category[1, e.RowIndex].Value.ToString()));//---------Sync
            }

            try
            {
                dgv_category.DataSource = null; //here Throwing exception

                u.operationOnDataBase(sqlquery, 3);
                dgv_category.DataSource = u.dt;


            }
            catch (InvalidOperationException)
            {
                // exception
            }
        }
Run Code Online (Sandbox Code Playgroud)

异常 - 操作无效,因为它导致对SetCurrentCellAddressCore函数的可重入调用.

在System.Windows.Forms.Forms.DataGridView.set_DataSource的System.Windows.Forms.DataGridView.set_CurrentCell(DataGridViewCell值)处的System.Windows.Forms.DataGridView.SetCurrentCellAddressCore(Int32 columnIndex,Int32 rowIndex,Boolean setAnchorCellAddress,Boolean validateCurrentCell,Boolean throughMouseClick) (对象值)

J. *_*len 0

不是直接设置DataSource,而是将DataSource设置为BindingSource,然后更改BindingSource.DataSource?

例如

//create bindingSource in the WinForms Designer
Run Code Online (Sandbox Code Playgroud)

然后...

try
{
   dgv_category.DataSource = null;
   dgv_category.Rows.Clear();
}
catch{}
bindingSource.DataSource = ut.dt;
dgv_category.DataSource = bindingSource;
bindingSource.ResetBindings(true);
Run Code Online (Sandbox Code Playgroud)