Search code examples
c#focuswpfdatagrid

Selecting and Focusing a Datagrid based on a variable


I want to keep this short and sweet. I can't figure out how to set focus and go to a certain row based on a user input, either like TextBox or a ComboBox. I keep trying different ways to try and write it but with no success. I have a combobox that when they insert a input like the id of 1567, I want the datagrid to find the row that has the variable id of 1567. I know this has had to be done before since it seems like something people would really use in a application.

To clarify more

I have this table

ID FirstName LastName Comments
123 Kyle        Bro     Comments???
145 Zach        Gred    Something??
178 Derrick     Davidson More??

I want to select the row where the ID field equals 145, not the actual row number which would be 1. I am pulling the data from a database, so I want to focus based on a cell not the row ID.

Thanks to D_Learning I got it to select with code

try
{
     if(dataGrid2.SelectedItem == null)
     {
         dataGrid2.SelectedItem = dataGrid2.Items.GetItemAt(0);
     }
     var selectedObj = dataGrid2.Items.Cast<DataRowView>().FirstOrDefault(a => a[0].ToString() == IDComboBox.Text);
     if (selectedObj != null)
     {
          dataGrid2.SelectedItem = selectedObj;
          dataGrid2.ScrollIntoView(selectedObj);
          dataGrid2.Focus();
     }
}
catch (InvalidOperationException  e)
{

}

My issues have been resolved with adding the dataGrid2.SelectedItem = dataGrid2.Items.GetItemAt(0); and checking for null.


Solution

  • I think you can achieve what you are looking for as below:

    var selectedObj = dgGrid.Items.Cast<YourClass>().First(a=> a.ID = txtFilter.Text);
    if(selectedObj != null)
        dgGrid.SelectedItem =  selectedObj;
    

    Please let me know if above doesn't work for you.