Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArgumentOutOfRangeException in DataGridCellsPanel.BringIndexIntoView when pressing enter on a WPF Datagrid?

I have this WPF DataGrid in a data template:

<DataGrid
    CanUserAddRows="False" CanUserDeleteRows="False" CanUserReorderColumns="False"
    CanUserSortColumns="False"
    SelectionMode="Single" SelectionUnit="FullRow" GridLinesVisibility="Horizontal"
    IsEnabled="{Binding Enabled}"
    ItemsSource="{Binding ValuesDataTable}"
    CellEditEnding="DataGrid_CellEditEnding"/>

Here's the event handler:

private void DataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
    if (e.EditAction == DataGridEditAction.Commit)
    {
        var textBox = e.EditingElement as TextBox;
        var dataGrid = (DataGrid)sender;
        var viewModel = dataGrid.DataContext as IHasEditableCell;
        viewModel.EditCell(e.Row.GetIndex(), e.Column.DisplayIndex, textBox.Text);
        dataGrid.CancelEdit();
    }
}

The key to this is that viewModel.EditCell raises a PropertyChanged event on the ValuesDataTable property of the view model that the DataGrid is binding to.

When I edit a cell and click off of it, it works fine. However, when I edit a cell and press Enter at the end of the edit, I get this runtime exception:

System.ArgumentOutOfRangeException was unhandled
  Message=Specified argument was out of the range of valid values.
Parameter name: index
  Source=PresentationFramework
  ParamName=index
  StackTrace:
       at System.Windows.Controls.DataGridCellsPanel.BringIndexIntoView(Int32 index)
       at System.Windows.Controls.Primitives.DataGridCellsPresenter.ScrollCellIntoView(Int32 index)
       at System.Windows.Controls.DataGrid.ScrollCellIntoView(Object item, DataGridColumn column)...

... which is weird. Any ideas how I can get around this?

like image 851
Scott Whitlock Avatar asked Mar 08 '11 19:03

Scott Whitlock


2 Answers

I had a similar problem when calling myDataGrid.ScrollIntoView(object item) directly from my code. I fixed it by calling myDataGrid.UpdateLayout() just before. You might want to give that a try if applicable.

like image 86
SuperOli Avatar answered Sep 19 '22 23:09

SuperOli


I have precisely this problem and still don't know why it happens. Rather unsatisfactorily, I ended up working around it by catching the enter key and manually commiting the edit.

    private void MyDataGrid_OnPreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Return)
        {
            e.Handled = true;
            MyDataGrid.CommitEdit();
        }
    }
like image 40
quarkonium Avatar answered Sep 22 '22 23:09

quarkonium