KyloRen KyloRen - 12 days ago 7
C# Question

How to programmaticly select DataGrid row with criteria?

Is there a way to select a DataGrid row by referencing the row ID?

I am selecting a DataGrid programatically via the code below,

public static void GetFocusOfSelectedRow(DataGrid datagrid)
{
object oItem = datagrid.Items[0];
datagrid.SelectedItem = oItem;
datagrid.ScrollIntoView(oItem);
}


This just selects the first row in the DataGrid.

I was hoping to be able to specify which row to select by using the primary key. ie, say a row has a primary key ID of
123456
. How could I get the rows index number with the ID of
123456
via LINQ or some other way?

Answer

You have to cast your items collection to a collection of Type that you know it has a property you want to filter.

Try

public static void GetFocusOfSelectedRow(DataGrid datagrid)
    {
        ItemCollection items = datagrid.Items;
        List<SomeType> collection = new List<SomeType>();

        foreach (var item in items)
        {
            SomeType obj = item as SomeType ;
            if(obj != null)
                collection.Add(obj);
        }

        SomeType result = collection.Where(a => a.SomeProperty == SomeValue)
            .FirstOrDefault();

        datagrid.SelectedItem = result;
        datagrid.ScrollIntoView(result);
    }