DataGrid Enter key press causing InvalidOperationException?

Nov 27, 2008 at 8:55 AM
I ran into an interesting issue with the V1 DataGrid. I have it bound to an ObservableCollection<T> which contains the data; nothing special there. When I add a new row and press Enter to move to the next row, I get an InvalidOperationException with the message "Added item does not appear at given index 'nn'.", with "nn" being the 0-based row index in question. The thing is, the record does get added, is saved to the underlying data storage (database by way of web service in my case) and is read back properly. If I simply resume program execution (pressing F5 in Visual Studio) when the exception gets thrown, I get no further errors and things work just fine. Since none of my own code is involved in handling the key press event within the data grid, I ended up modifying DataGrid.cs to fix this around line 3402.

            if (IsEditingRowItem)
                    EditableItems.CommitNew(); // this is the only statement in the else{} block in the V1 DataGrid code
                catch (InvalidOperationException exception)
                    /* If the user adds a new row and press Enter to save, this causes an
                     * InvalidOperationException Message="Added item does not appear at given index 'nn'.",
                     * even though the item is right there both in the UI and properly persisted across
                     * refreshes/reloads. (Interestingly, tabbing across fields appears to work fine.)
                     * Since there is no code outside of DataGrid involved in that execution path, it
                     * cannot easily be handled by the host application. Therefore, quietly swallow such
                     * exceptions here, but re-throw anything else.

                    if (exception.Message.Substring(0, "Added item does not appear at given index '".Length).Equals("Added item does not appear at given index '"))
                        // Do nothing

The XAML in question is nothing unusual:

    <toolkit:DataGrid BorderThickness="0" Margin="0" Name="dataGrid" Loaded="dataGrid_Loaded" AutoGenerateColumns="False" IsReadOnly="False" SelectionUnit="Cell" AlternationCount="1" CanUserAddRows="True" CanUserResizeRows="False" ClipboardCopyMode="IncludeHeader" FrozenColumnCount="1" IsTextSearchEnabled="True" RowDetailsVisibilityMode="VisibleWhenSelected" RowEditEnding="dataGrid_RowEditEnding" MouseDoubleClick="dataGrid_MouseDoubleClick" BeginningEdit="dataGrid_BeginningEdit" MouseRightButtonUp="dataGrid_MouseRightButtonUp" SelectionMode="Single">
                <MenuItem ...... />
            <toolkit:DataGridTextColumn Header="..." x:Name="..." Width="75" Binding="{Binding Path=...}" IsReadOnly="False" ........ />

I can't imagine that this is an unusual use case, which brings me to the question: what, if anything, am I doing wrong?