行验证事件期间发生InvalidOperationException

时间:2018-09-11 22:08:47

标签: c# invalidoperationexception

我有2个绑定到BindingDataSources的DataGridViews,它们保存来自数据库包装器类的DataTables,该类使用SqlDatabaseAdapter来管理数据。

我试图允许用户添加/编辑行,然后将更改立即提交到数据库,而无需单击保存按钮。我使用RowValidated事件写回SQL,但是我发现,如果在单个会话中两次更改同一行,则会出现并发错误。为了解决这个问题,我在每次更新后都刷新了数据源。

这适用于一个表,但不适用于第二个表。通过研究,我发现例外是正确的行为。问题是2折。
1.为什么完全可以使用?
2.实现此目标的正确方法是什么?

相关代码:

private void RefreshWebDisplay()
{
    webDisplay = new WebDisplay(_configString);

    BindingSource bsDisplay = new BindingSource();
    bsDisplay.DataSource = webDisplay.Display;
    dgvWebDisplay.DataSource = bsDisplay;  //This line does NOT throw an exception
    dgvWebDisplay.Refresh();

    BindingSource bsPages = new BindingSource();
    bsPages.DataSource = webDisplay.Pages;
    dgvWebPages.DataSource = bsPages;  //This line throws an InvalidOperationException
    dgvWebPages.Refresh();
}

//I combined the RowValidated event functions for testing, trying to eliminate all differences. 
private void dgvWebDGV_RowValidated(object sender, DataGridViewCellEventArgs e)
{
    DataGridView dgv = sender as DataGridView;
    if (dgv.NewRowIndex != e.RowIndex)
    {
        (dgv.DataSource as BindingSource).EndEdit();

        if (((dgv.DataSource as BindingSource).DataSource as DataTable).GetChanges() != null)
        {                
            if (dgv == dgvWebDisplay)                    
                webDisplay.Display = (dgv.DataSource as BindingSource).DataSource as DataTable;
            else if (dgv == dgvWebPages) 
                webDisplay.Pages = (dgv.DataSource as BindingSource).DataSource as DataTable;                      

             RefreshWebDisplay();
        }
    }
}

class WebDisplay
{
    ...
    public DataTable Display
    {
        get
        {
            DataTable dt = new DataTable();
            DisplayAdapter.Fill(dt);
            return dt;
        }
        set
        {
            if (value != null)
                DisplayAdapter.Update(value);

        }
    }
    public DataTable Pages
    {
        get
        {
            DataTable dt = new DataTable();
            PageAdapter.Fill(dt);
            return dt;
        }
        set
        {
            if(value != null)
                PageAdapter.Update(value);
        }
    }
    ...
}

1 个答案:

答案 0 :(得分:0)

在对两个DataGridView进行逐行比较时,我发现我对具有所需行为的那个设置了AutoGenerateColumns为false,对第二个DataGridView进行了同样的设置后,它也表现正常。

相关问题