WPF Datagrid set selected row

Tony The Lion picture Tony The Lion · Dec 29, 2009 · Viewed 116.9k times · Source

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.

Answer

serge_gubenko picture serge_gubenko · Dec 29, 2009

please check if code below would work for you; it iterates through cells of the datagris'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;
    }
}

hope this helps, regards