Reputation: 1011
how Select the row index in datagrid ?
The event SelectionChanged
The following code does not work :
private DataGridRow dgr = new DataGridRow();
private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
this.dgr = this.dataGrid.ItemContainerGenerator.ContainerFromItem(this.dataGrid.SelectedItem) as DataGridRow;
MessageBox.Show(this.dgr.GetIndex().ToString());
}
Upvotes: 2
Views: 8191
Reputation: 10172
This is a late answer, but this is how I accomplished it. This gives you index of every selected row in the DataGrid (dgQuery is the name of my DataGrid):
foreach (var selection in dgQuery.SelectedItems)
{
DataRowView row = (DataRowView)item;
int index = Convert.ToInt32(row.Row[0]) - 1;
}
It gives 1 at index 0, so we need to subtract 1 at every index.
.Row[0]
Is actually a column (in my head)... of that DataRowView, not sure why it's called a row. You can change it to [1], [2] and so on to view other cells within that row.
With this solution, you don't need a collection, array, nothing of that sort. You just work with what's at hand and make use of existing code.
The huge plus side of this implementation, at least for me, was the fact that it goes through selected items in the order they were selected. This can be a very powerful tool if you wish to know the order of user's selection.
I'm posting this because I just spent over 4 hours looking for a solution. I even gave up on check boxes because I don't have enough time to implement those to work well... maybe down the road.
Upvotes: 1
Reputation: 8608
My answer is late, but I hope it still will be useful for people who found this post from search engines. This is more general solution which also helps to define indexes of all the selected rows.
List<int> RowIndexes = new List<int>();
int SelectedItemsCount = yourDataGrid.SelectedItems.Count;
for (int i = 0; i < SelectedItemsCount ; i++)
{
RowIndexes.Add(yourDataGrid.Items.IndexOf(yourDataGrid.SelectedItems[i]));
}
And now RowIndexes contains all indexes of the selected rows. Just put the code inside the event you wish, that's all.
Upvotes: 2
Reputation: 19895
The reason why above code would not work is because wpf data grid is virtualized and it may not return the row using the itemContainerGenerator.ContainerFromItem because it may be lying outside the scroll view.
For this you will have to use the datagrid's items collection and the IndexOf call using selected item.
private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var dg = sender as DataGrid;
MessageBox.Show(dg.Items.IndexOf(dg.SelectedItem).ToString());
}
Upvotes: 3