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.
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.
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.
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.
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With