I have created a WPF application that loads 2 DataGrids with data from SqlClient DataTables. I have the method below that compares the two tables. It was working fine, but I must have changed something in the code that broke it. Now the dataGridRow1 and dataGridRow2 variables are always null. How can I get the DataGridRow from the DataRowView?
private void CompareDataTables(string primaryKey)
{
foreach (DataRowView dataRowView1 in DataGrid1.ItemsSource)
{
DataGridRow dataGridRow1 = DataGrid1.ItemContainerGenerator.ContainerFromItem(dataRowView1) as DataGridRow;
if (dataGridRow1 != null)
{
int primaryKeyValue1 = (int)dataRowView1.Row[primaryKey];
foreach (DataRowView dataRowView2 in DataGrid2.ItemsSource)
{
//DataRowView dataRowView2 = (DataRowView)dataGridRow2.Item;
int primaryKeyValue2 = (int)dataRowView2.Row[primaryKey];
if (primaryKeyValue1 == primaryKeyValue2)
{
foreach (DataGridColumn column in DataGrid1.Columns)
{
DataGridRow dataGridRow2 = DataGrid2.ItemContainerGenerator.ContainerFromItem(dataRowView2) as DataGridRow;
if (dataGridRow2 != null)
{
FrameworkElement frameworkElement1 = column.GetCellContent(dataGridRow1);
FrameworkElement frameworkElement2 = GetFrameworkElement(DataGrid2, dataGridRow2, (String)column.Header);
if (frameworkElement1 is TextBlock && frameworkElement2 is TextBlock)
{
TextBlock textBlock1 = frameworkElement1 as TextBlock;
TextBlock textBlock2 = frameworkElement2 as TextBlock;
if (textBlock1.Text != textBlock2.Text)
{
textBlock1.Background = Brushes.LightSalmon;
textBlock2.Background = Brushes.LightSalmon;
}
}
}
}
break;
}
}
}
}
}