WPF DataGrid: How to Determine the Current Row Index?

Travis Banger picture Travis Banger · Nov 24, 2013 · Viewed 54.2k times · Source

I am trying to implement a very simple spreadsheet functionality based on a DataGrid.

  1. The user clicks on a cell

  2. The user types a value and presses return

  3. The current row is scanned and any cell formula that depends on the clicked cell is updated.

This seems to be the best event handler for my requirements:

private void my_dataGrid_CurrentCellChanged(object sender, EventArgs e)

Question: How do I detect the row index of the current row?

Answer

Grant Winney picture Grant Winney · Nov 24, 2013

Try this (assuming the name of your grid is "my_dataGrid"):

var currentRowIndex = my_dataGrid.Items.IndexOf(my_dataGrid.CurrentItem);

Normally, you'd be able to use my_dataGrid.SelectedIndex, but it seems that with the CurrentCellChanged event, the value of SelectedIndex always displays the previously selected index. This particular event seems to fire before the value of SelectedIndex actually changes.