Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get DataGrid row by index

Tags:

c#

.net

wpf

xaml

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.

like image 938
Nilesh Barai Avatar asked Jan 28 '14 18:01

Nilesh Barai


1 Answers

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);
like image 150
Mike Schwartz Avatar answered Oct 28 '22 15:10

Mike Schwartz