I want to pass a value and a column index to a method that will programmatically select the rows in a DataGrid control that match the value in the given column.
My code is like this:
private void HighlightSelections(string selection, int colIndex)
{
mtoDG.UnselectAll();
for(int i = 0; i < mtoDG.Items.Count; i++)
{
DataGridRow row = mtoDG.ItemContainerGenerator.ContainerFromIndex(i) as DataGridRow;
if (mtoDG.Columns[colIndex].GetCellContent(row) is TextBlock cellContent && cellContent.Text.Equals(selection))
{
object item = mtoDG.Items[i];
mtoDG.SelectedItems.Add(item);
}
}
}
I have found that this method only works if the entirety of the datagrid is displayed on the screen. If there are any undisplayed rows due to space constraint then it will throw a nullexception error.
So my question is is there anything I can change in my code to make it work even if there are unseen rows in the display area?