select a datagrid cell that contains a given value in wpf

泄露秘密 提交于 2019-12-25 07:58:51

问题


I bound a DataTable to a datagrid in wpf. The first column has unique values. Now I would like to autoselect a cell in the second column whose first column cell has the given value. How should I achieve that? For example,here is my datagrid:

Name | Age
cat     |  2
dog    | 3

When user input 'dog', I will need the '3' to be selected.

I tried the method show here:
How to select a row or a cell in WPF DataGrid programmatically?
However, I cannot figure out the displaying row number. Even though I know the row number of the dataTable, the display number can be different since I allow users to sort the table.

Thanks a lot.


回答1:


Set your grid's SelectionUnit property to "Cell", and assuming you feed the DataGrid with the table's DefaultView:

private void button1_Click(object sender, RoutedEventArgs e)
{
  // Search for the source-row.
  var Element = MyDataTable.AsEnumerable()
    .FirstOrDefault(x => x.Field<string>("Name") == "horse");

  if (Element == null) return;

  // Found the row number in the DataGrid
  var RowOnGrid = MyGrid.Items.OfType<DataRowView>()
    .Select((a, Index) => new { data=a.Row, index = Index })
    .Where(x=> x.data == Element)
    .Select(x => x.index)
    .FirstOrDefault();

  // Assuming the desired column is the second one.
  MyGrid.SelectedCells.Clear();
  MyGrid.SelectedCells.Add(new DataGridCellInfo(MyGrid.Items[RowOnGrid], MyGrid.Columns[1]));
}

It should work even if you re-sort the rows.



来源:https://stackoverflow.com/questions/10339294/select-a-datagrid-cell-that-contains-a-given-value-in-wpf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!