Search code examples
wpfdatagrid

WPF datagrid 'newitemplaceholderposition' is not allowed during a transaction begun by 'addnew'


I have a tabControl on a WPF form.

In one of the Tab Items I have a User Control that contains a DataGrid which has CanUserAddRows="True". The user can type data in the column and when they press [enter], a new row is created.

The problem is when I type data into the new row and then change tabs I get this exception: "WPF datagrid 'newitemplaceholderposition' is not allowed during a transaction begun by 'Addnew' "

Any suggestions how to avoid it?

I have tried to put dg.CommitEdit() on usercontrol.Unloaded(). I don't get the exception, but I also don't get the new row.


Solution

  • I ran into the same problem...here are some snippets describing how I solved it. Note that in my case I wanted to reject the changes to avoid the error. If you want to commit the changes, this may lead you in the right direction.

    1a) Use the InitializingNewItem event on the datagrid to capture the adding row.

    private void mydatagrid_InitializingNewItem(object sender, InitializingNewItemEventArgs e)
        {
            _viewmodel.NewRowDefaults((DataRowView)e.NewItem);
        }
    

    1b) In this case, I'm calling a method in my view model to populate row defaults and save a reference to the row.

        private DataRowView _drvAddingRow { get; set; }
        public void NewRowDefaults(DataRowView drv)
        {
            _drvAddingRow = drv;
            ...
        }
    

    2) Then when you need to reject the change (before notifying property changes or whatever your case is), use the CancelEdit method on the captured datarowview.

     _drvAddingRow.CancelEdit();