InvalidOperationException

InvalidOperationException

当我更改要更新的单元格值并直接单击菜单栏项以打开新的Winform时,抛出InvalidOperationException

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

最佳答案

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

例如

//create bindingSource in the WinForms Designer

然后...
try
{
   dgv_category.DataSource = null;
   dgv_category.Rows.Clear();
}
catch{}
bindingSource.DataSource = ut.dt;
dgv_category.DataSource = bindingSource;
bindingSource.ResetBindings(true);

关于c# - 数据网格 View CellValueChanged事件引发InvalidOperationException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39574311/

10-10 19:04