Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Datagrid set selected row

Tags:

How do I use the Datagrid.SelectedItem to select a row programmatically?

Do I first have to create a IEnumerable of DataGridRow objects and pass the matching row to this SelectedItem property or how do I do it?

EDIT:

I need to match the cell content of the first columns cell with a TextBox.Text first, before selecting the row.

like image 766
Tony The Lion Avatar asked Dec 29 '09 18:12

Tony The Lion


People also ask

How to select row in DataGrid in WPF?

WPF DataGrid (SfDataGrid) allows you to select one or more rows or cells. For selecting specific row or group of rows you have to set SelectionUnit as Row and for selecting a specific cell or group of cells you have to set SelectionUnit as Cell or Any. In SelectionUnit.

How to select cell in DataGrid WPF?

Selecting a single cell The difference is that you add a System. Windows. Controls. DataGridCellInfo object to the DataGrid's SelectedCells collection for each cell that you want to select, instead of setting its SelectedItem property or adding items to its SelectedItems collection.

How to remove Selected row from DataGrid in WPF?

You can access the currently selected item of a DataGrid using the SelectedItem property. After the first line you need to extract the information (e.g. some Id) from the item in order to delete it in the database. Usually you cast the SelectedItem to the object you used to bind to the grid. See also this response.


1 Answers

My code iterates through cells of the datagrid's first column and checks if cell content equals to the textbox.text value and selects the row.

for (int i = 0; i < dataGrid.Items.Count; i++) {     DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(i);     TextBlock cellContent = dataGrid.Columns[0].GetCellContent(row) as TextBlock;     if (cellContent != null && cellContent.Text.Equals(textBox1.Text))     {         object item = dataGrid.Items[i];         dataGrid.SelectedItem = item;         dataGrid.ScrollIntoView(item);         row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));         break;     } } 
like image 89
serge_gubenko Avatar answered Sep 21 '22 03:09

serge_gubenko