Shahin
Shahin

Reputation: 12843

WPF : Get index of clicked / selected cell on DataGrid

How do I get index of clicked / selected cell on DataGrid ?
My DataGrid columns generated automatically and I don't want to use any DataTemplate .

<DataGrid ItemsSource="{Binding Table, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, IsAsync=True}"
          AutoGenerateColumns="True">
</DataGrid>

Upvotes: 7

Views: 15723

Answers (3)

Tharmas
Tharmas

Reputation: 1

I had the same problem with the row index, and the answer given by BR1COP was the only one that worked for me. I didn't use the loop as I only needed the index of one cell, any selected cell. So I used it like this:

DataGridCellInfo cell = myGrid.SelectedCells[0];
int rowIndex = dividingGrid.Items.IndexOf(cell.Item);

Upvotes: 0

BR1COP
BR1COP

Reputation: 349

This is the solution I found, when selection unit is "cell" and you need to loop through the selected cells, getting row and column index. I have a DataGrid with textcolumn only, and a datatable (creted from a csv file) as itemssource.

 For Each cell As DataGridCellInfo In dataGrid1.SelectedCells

         MsgBox(cell.Column.DisplayIndex)
         MsgBox(dataGrid1.Items.IndexOf(cell.Item))
 Next

Upvotes: 2

Ivan Peric
Ivan Peric

Reputation: 4403

DataGrid x = (DataGrid)this.FindName("myDataGrid");
var index = x.SelectedIndex;

There are also other usefull properties:

x.CurrentColumn;
x.CurrentItem;
x.SelectedItem;
x.SelectedValue;

Upvotes: 12

Related Questions