0

我目前正在使用 WPF 中的 DataGrid。在 CellEditEnding 事件中,我捕获了 DBConcurrencyException - 第一次效果很好。为了检查,我加载程序,然后更改数据库中的数据。接下来我更改 DataGrid 中的数据并触发异常。在 catch 子句中,我重新加载表数据。到目前为止一切正常,但是当我重复该过程时,不再触发异常。这是我重新加载数据的代码:

    private void reloadData()
    {
        rebuildAdapter();
        tables[gridNumber] = new DataTable();
        adapters[gridNumber].Fill(tables[gridNumber]);
        grids[gridNumber].ItemsSource = tables[gridNumber].DefaultView;
    }

我错过了什么?

4

1 回答 1

0

好的,现在解决了。我忽略了当抛出 DBConcurrencyException 时,布尔值“isManualEditCommit”也需要再次设置为 false。有兴趣的可以看下面的代码:

private void grids_CellEditEnding(object sender, Microsoft.Windows.Controls.DataGridCellEditEndingEventArgs e)
{
    try
    {
        Microsoft.Windows.Controls.DataGrid grid = (Microsoft.Windows.Controls.DataGrid)sender;
        gridNumber = Convert.ToInt16(grid.Name.Substring(grid.Name.Length - 1, 1)) - 1;

        if (!isManualEditCommit)
        {
            isManualEditCommit = true;
            grid.CommitEdit(Microsoft.Windows.Controls.DataGridEditingUnit.Row, true);

            using (SqlConnection con = new SqlConnection(GUI.dictSettings["connectionString"]))
            {
                con.Open();

                SqlCommandBuilder com = new SqlCommandBuilder(adapters[gridNumber]);
                adapters[gridNumber].UpdateCommand = com.GetUpdateCommand();
                adapters[gridNumber].Update(tables[gridNumber]);

                tables[gridNumber].AcceptChanges();
                con.Close();
            }
            isManualEditCommit = false;
        }

    }
    catch (DBConcurrencyException ex)
    {
        isManualEditCommit = false;
        reloadData();

    } catch(Exception ex){
        isManualEditCommit = false;
        reloadData();
    }
}
于 2013-11-05T23:16:25.403 回答