I am trying to implement a very simple spreadsheet functionality based on a DataGrid.
The user clicks on a cell
The user types a value and presses return
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?
1.When click on the Cell inside the Datagrid, Get the CurrentCell info
2.From the DatagridCellInfo, we can find Column and Row index of particular cell
The accepted solution will work until you have no reference-duplicates in the
ItemsSource
, otherwise you will get index of the object's first occurrence.The solution from BRAHIM Kamel will work until you have a selection, otherwise(if you click twice and deselect a cell/row) you will not have a
SelectedIndex
.With
YourDataGrid.ItemContainerGenerator.ContainerFromItem( _dataItemFromCurentCell ) as DataGridRow
you will get by duplicates always the last occurrence of data item.I would handle
DataGrid.PreviewMouseLeftButtonDown
event and search in handler the visual tree up to aDatagridRow
, which hasDatagridRow.GetIndex()
method. So you will get always the right row index.Try this (assuming the name of your grid is "my_dataGrid"):
Normally, you'd be able to use
my_dataGrid.SelectedIndex
, but it seems that with theCurrentCellChanged
event, the value of SelectedIndex always displays the previously selected index. This particular event seems to fire before the value of SelectedIndex actually changes.Hi you can do something like this to do your spreadsheed
but if you want a more elaborated example this is how you can do it
Hope this help