Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF : Get index of clicked / selected cell on DataGrid

Tags:

wpf

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>
like image 524
Shahin Avatar asked Sep 04 '13 14:09

Shahin


2 Answers

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

There are also other usefull properties:

x.CurrentColumn;
x.CurrentItem;
x.SelectedItem;
x.SelectedValue;
like image 75
Ivan Peric Avatar answered Oct 27 '22 15:10

Ivan Peric


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
like image 39
BR1COP Avatar answered Oct 27 '22 14:10

BR1COP