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

本文关键字:InvalidOperationException 事件 cellvaluechange 数据网 网格 视图 数据 | 更新日期: 2023-09-27 18:07:31

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

Exception—操作无效,因为它会导致SetCurrentCellAddressCore函数的可重入调用。

System.Windows.Forms.DataGridView.SetCurrentCellAddressCore (Int32columnIndex, Int32 rowIndex, BooleanvalidateCurrentCell,布尔值,通过mouseclick)System.Windows.Forms.DataGridView.set_CurrentCell (DataGridViewCell在System.Windows.Forms.DataGridView.set_DataSource(对象值)

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

不直接设置数据源,而是将数据源设置为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);

试试这个

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; //you don't need to set it to null just remove it
            //try set empty data table 
            DataTable dt = new DataTable();
           dgv_category.DataSource = dt;
            u.operationOnDataBase(sqlquery, 3);
            dgv_category.DataSource = u.dt;

        }
        catch (InvalidOperationException)
        {
            // exception
        }
    }
相关文章:
  • 没有找到相关文章