2

I have a DataGrid which is filled with a List of Objects. It has a MouseDoubleClick event.

I am trying to find out which row exactly of the DataGrid was clicked.

So far I've tried this:

private void DataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    DataGridRow Row = sender as DataGridRow;
    int RowNumber = Row.GetIndex();
    //dostuff with RowNumber ;
}

which sadly gets me a System.NullReferenceException.

xaml for completeness:

<DataGrid x:Name="DataGrid_Table" Grid.Row="3" AutoGenerateColumns="True" ItemsSource="{Binding}" IsReadOnly="True"
      MouseDoubleClick="DataGrid_MouseDoubleClick" FontSize="22" />
Nkosi
  • 235,767
  • 35
  • 427
  • 472
Stefan D
  • 23
  • 3
  • 1
    You get null exception because it is the grid (DataGrid) sending the event and you try to convert/cast it to a `DataGridRow`. You probably want the `DataGrid.SelectedIndex` which would indicate the index of the `SelectedItem` or currently selected row of the grid. Note that that index is zero indexed. – Nkosi Jun 17 '17 at 12:03
  • 1
    Possible duplicate of [WPF datagrid selected row clicked event ?](https://stackoverflow.com/questions/3120616/wpf-datagrid-selected-row-clicked-event) – Alexander Jun 17 '17 at 13:01

1 Answers1

2

You get null exception because it is the grid (DataGrid) sending the event and you try to convert/cast it to a DataGridRow. You probably want the DataGrid.SelectedIndex which would indicate the index of the SelectedItem or currently selected row of the grid. Note that that index is zero indexed.

private void DataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e) {
    var dataGrid = sender as DataGrid;
    if (dataGrid != null) {
        var index = dataGrid.SelectedIndex;
        //dostuff with index
    }
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472