9
votes

I am trying to obtain DataGridRow from my DataGrid based on index. I am using following code:

public DataGridRow GetGridRow(int index)
{
    DataGridRow row = (DataGridRow)DG_Statement.ItemContainerGenerator.ContainerFromIndex(index);
    if (row == null)
    {
        // May be virtualized, bring into view and try again.
        DG_Statement.UpdateLayout();
        DG_Statement.ScrollIntoView(DG_Statement.Items[index]);
        row = (DataGridRow)DG_Statement.ItemContainerGenerator.ContainerFromIndex(index);
    }
    return row;
}

Ref Link - Get row in datagrid

But unfortunately its returning a null object of DataGridRow. If I check the Items[] property of my grid I could see 13 items.

Need suggestion on how to obtain the Grid Row as I want to change color of top 2 and bottom 2 rows of my data grid.

Any help is appreciated. Thanks!!

Adding Screenshot of DataGrid Items

enter image description here

Important Update

If I call GetGridRow() from the SelectedIndexChanged Event of the Grid it works flawlessly.

On the other hand, if I call it after I construct the object of the page on which my grid is displayed it returns row object as NULL.

2
Where does this method live? Code behind or in a view model? - Mike Schwartz
This was already asked here on Stack overflow. - AR5HAM
I have provided this link in the reference and using the code suggested in that post. But I am getting null object of Row that's where I am stuck. - Nilesh Barai
Sounds like at that point its not been initialized. - Mike Schwartz
@MikeSchwartz: can you please suggest any workaround for achieving this? - Nilesh Barai

2 Answers

9
votes

So if its in the code behind. You can just get the selected index of the DataGrid. I've named the datagrid dataGrid as an example.

var rowIndex = dataGrid.SelectedIndex;

var row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(selectedIndex);
0
votes

Check to make sure the index you're passing in is actually within bounds.