In C# WPF, Null reference exception creates when datagrid rows are not visible within grid (It occurs when there are rows which can be seen by scrolling down the datagrid) how can I avoid that? I am new to WPF.
My Code:
foreach (DataRowView dr in datagrid.ItemsSource)
{
DateTime date2 = Convert.ToDateTime(dr["date2"]);
DateTime currentdate = DateTime.Now;
DateTime upcomingdate = DateTime.Now.AddDays(+5);
if (date2 < currentdate)
{
var Srow = datagrid.ItemContainerGenerator.ContainerFromItem(dr) as DataGridRow;
Srow.Foreground = Brushes.Red;
}
else if (date2 < upcomingdate)
{
var Srow1 = datagrid.ItemContainerGenerator.ContainerFromItem(dr) as DataGridRow;
Srow1.Foreground = Brushes.Green;
}
}