Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why ItemContainerGenerator.ContainerFromIndex() returns null and how to avoid this behavior?

I'm using this snippet to analyze the rows I've selected on a datagrid.

for (int i = 0; i < dgDetalle.Items.Count; i++)
{
    DataGridRow row = (DataGridRow)dgDetalle.ItemContainerGenerator.ContainerFromIndex(i);
    FrameworkElement cellContent = dgDetalle.Columns[0].GetCellContent(row);
    // ... code ...
}

The cycle runs smoothly, but when processing certain indexes, the second line throws a null exception. MSDN's documentation says that ItemContainerGenerator.ContainerFromIndex(i) will return null if 'if the item is not realized', but this doesn't help me to guess how could I get the desired value.

How can I scan all the rows? Is there any other way?

UPDATE

I'm using this snippet to read a CheckBox as explained here. So I can't use binding or ItemSource at all unless I change a lot of things. And I cannot. I'm doing code maintenance.

like image 245
JPCF Avatar asked May 14 '12 21:05

JPCF


2 Answers

Try this,

DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
        if (row == null)
        {
                          grid.UpdateLayout();
            grid.ScrollIntoView(grid.Items[index]);
            row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
        }
like image 94
itzmebibin Avatar answered Sep 30 '22 07:09

itzmebibin


The DataGrid is virtualizing the items, the respective rows (i.e. containers) are only created when the row is in view.

You could either turn off virtualization (which makes the first time loading very slow if you have many items, also the memory usage will be higher) or you just iterate over the data and check the values of the data objects' properties which should be bound to the data-grid. Usually you should not need the UI elements at all...

like image 45
H.B. Avatar answered Sep 30 '22 06:09

H.B.