Stefan D
Stefan D

Reputation: 23

How to tell which row of DataGrid was clicked?

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" />

Upvotes: 2

Views: 1704

Answers (1)

Nkosi
Nkosi

Reputation: 247531

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
    }
}

Upvotes: 2

Related Questions