Search code examples
c#wpfdatagridindices

How to get all selected indices in a datagrid


I have a datagrid with the option SelectionMode = DataGridSelectionMode.Extended.

With that I can select various row.

enter image description here

I would like to know the indices of the selected rows. I am aware that I can get dtg_ExecutionTimes_PpDescriptions.SelectedItems but I am not able to retrieve the indices from that list. For example in the picture it is 1 and 3 (or 0 and 2)

Thanx


Solution

  • There are different ways, if you don't have reference duplicates in your items source (what is usually the case), then you can iterate through the items and get the indexes:

    var selIndexes = new List<int>();
    foreach (var selItem in dtg_ExecutionTimes_PpDescriptions.SelectedItems)
    {
        selIndexes.Add(dtg_ExecutionTimes_PpDescriptions.Items.IndexOf(selItem));
    }