DataGrid DataTable绑定 - 获取选定的DataTable行索引

时间:2014-08-04 17:58:34

标签: c# binding datagrid datatable indexing

我有一个DataTable绑定到WPF中的DataGrid。假设这个DataTable填充了以下内容:

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

代码如下:

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;

我的问题是,当用户开始通过DataGrid选择行时,如何获取 DataTable 的选定行索引列表? DataGrid 本身的选定行索引列表将毫无用处,因为特定列的排序会更改索引。

丹尼斯回答

List<int> SelectedIndexes = dataGrid
                              .SelectedItems
                              .Cast<DataRowView>()
                              .Select(view => dataTable.Rows.IndexOf(view.Row))
                              .ToList();

2 个答案:

答案 0 :(得分:1)

这样的事情:

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

答案 1 :(得分:0)

来自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]);
    }
  }
}