KyloRen KyloRen - 4 months ago 35
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;

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
. How could I get the rows index number with the ID of
via LINQ or some other way?


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


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)

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

        datagrid.SelectedItem = result;