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();
ItemsSource
, not theDataContext
? – Mike ZborayBinding="{Binding ID}"
) already, so setting the DataContext should do the trick. – jacobz