WPF DataGrid:DBConcurrencyException未在try catch中捕获

时间:2013-11-01 20:00:41

标签: c# wpf exception concurrency datagrid

我目前正在使用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;
    }

我错过了什么?

1 个答案:

答案 0 :(得分: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();
    }
}