简体   繁体   中英

WPF DataGrid: DBConcurrencyException not caught in try catch

I´m currently working with a DataGrid in WPF. In the CellEditEnding event im catching the DBConcurrencyException - which works out fine the first time. To check, I load the program and then change the data in the Database. Next I change the data in the DataGrid and the exception is fired. In the catch clause I reload the table data. All ok so far, but when I repeat the process, the exception isn´t fired anymore. Here´s my code to reload the data:

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

What am I missing?

Ok, solved that now. I had overlooked that the boolean value "isManualEditCommit" also needs to be set to false again when a DBConcurrencyException is thrown. For anyone interested, see code below:

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM