0

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;
            }

        }
Tharindu
  • 21
  • 6
  • Due to [virtualization](https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/optimizing-performance-controls?view=netframeworkdesktop-4.8), ContainerFromItem may return null. You should not set the Foreground in code behind. Instead, bind it to a property of the item class. You may use a Binding Converter to convert an arbitrary input value to a Brush. – Clemens Feb 08 '22 at 19:15
  • @Clemens Dear Clemens, Thank you for the reply! can you tell more about how to do that? sorry for asking. But I am very new to WPF. – Tharindu Feb 08 '22 at 20:55
  • There is really plenty of information available. May start reading here: [Data binding overview](https://learn.microsoft.com/de-de/dotnet/desktop/wpf/data/?view=netdesktop-6.0). – Clemens Feb 08 '22 at 20:58
  • Ok. I will check. Thank you for helping me! – Tharindu Feb 08 '22 at 21:05
  • Otherwise just try to set `VirtualizingPanel.IsVirtualizing="False"` on the DataGrid. – Clemens Feb 08 '22 at 21:06
  • Thank you for the help! Actually it worked when I set EnableRowVirtualization="False" on the DataGrid. – Tharindu Feb 08 '22 at 21:32
  • Sure, but you are switching off virtualization, which may have an impact on performance with large amounts of data. And accessing DataGridRows like this isn't recommended. Better search for a solution where you bind the Foreground property. – Clemens Feb 08 '22 at 21:47
  • Thanks for the information! I will check about that. – Tharindu Feb 09 '22 at 13:21

0 Answers0