1
votes

I've got a DataTable bound to a DataGrid in WPF. Let's say this DataTable is populated with following:

╔════════════╦════════════╦════════════╗
║  Header1   ║  Header2   ║  Header3   ║
╠════════════╬════════════╬════════════╣
║ Something1 ║ Something2 ║ Something3 ║
║ Something4 ║ Something5 ║ Something6 ║
║ Something7 ║ Something8 ║ Something9 ║
╚════════════╩════════════╩════════════╝

The code would be following:

DataTable dtTest = new DataTable();
dtTest.Columns.Add("Header1", typeof(string));
dtTest.Columns.Add("Header2", typeof(string));
dtTest.Columns.Add("Header3", typeof(string));

dtTest.Rows.Add("Something1", "Something2", "Something3");
dtTest.Rows.Add("Something4", "Something5", "Something6");
dtTest.Rows.Add("Something7", "Something8", "Something9");

// Bind to DataGrid
datagrid.DataContext = dtTest.DefaultView;

My question is, how do I get a list of selected row indexes of the DataTable as the user starts selecting rows through the DataGrid? A list of selected row indexes of the DataGrid itself would be useless, as sorting of a specific column would change the indexes.

Answer by Dennis

List<int> SelectedIndexes = dataGrid
                              .SelectedItems
                              .Cast<DataRowView>()
                              .Select(view => dataTable.Rows.IndexOf(view.Row))
                              .ToList();
2
Dude, I love how you built that screenshot with "═" ASCII characters. Reminds me of my QuickBasic days... - Federico Berasategui
Which, if any, of those columns contain unique values (or is some combination of those columns a unique value)? - Sven Grosen
If they did, I could do it with LINQ. But sadly they don't. - jacobz
Don't you want to set the datagrid's ItemsSource, not the DataContext? - Mike Zboray
My DataGrid's columns are bound to specific columms in XAML (e.g. Binding="{Binding ID}") already, so setting the DataContext should do the trick. - jacobz

2 Answers

1
votes

Something like this:

dataGrid
  .SelectedItems
  .Cast<DataRowView>()
  .Select(view => dataTable.Rows.IndexOf(view.Row));
0
votes

From codeproject:

private void btnProcessMedia_Click(object sender, RoutedEventArgs e)
{
  if (dgProjects.SelectedItems.Count > 0)
  {
    for (int i = 0; i < dgProjects.SelectedItems.Count; i++)
    {
      System.Data.DataRowView selectedFile = (System.Data.DataRowView)dgProjects.SelectedItems[i];
      string str = Convert.ToString(selectedFile.Row.ItemArray[10]);
    }
  }
}