简体   繁体   中英

Cannot add more than one row to datagrid with different colors WPF c#

I have a DataGrid that is bound to an ObservableCollection of JobItems. JobItems have a DueDate property, and depending on how close the currentDate gets to the DueDate, the row colors change accordingly. This works perfectly when the user adds items to the ObservableCollection through a UI, but it does not work when I create more than one dummy JobItem in the code behind to populate this datagrid at the start of the program. The first dummy I add, however, has no problems at all. This is important because I will eventually need this when I have my database in place.

This is what my code looks like behind:

ObservableCollection <JobItem> JobItemList = new ObservableCollection<JobItem>();
public AdminView(Employee currEmployee)
    {
        this.Title = "Administrator View - " + currEmployee.Name;
        InitializeComponent();
        jobItemDataGrid.DataContext = JobItemList;

        LoadDummies();


    }

    private void LoadDummies()
    {
        JobItem j1 = new JobItem();
        JobItem j2 = new JobItem();
        JobItem j3 = new JobItem();

        j1.WorkOrderNo = "W12-021";
        j2.WorkOrderNo = "W12-037";
        j3.WorkOrderNo = "W12-234";


        j1.DateReceived = DateTime.Now.ToString();
        j2.DateReceived = DateTime.Now.ToString();
        j3.DateReceived = DateTime.Now.ToString();

        j1.DueDate = (DateTime.Now.AddDays(2)).ToString();
        j2.DueDate = (DateTime.Now.AddDays(2)).ToString();
        j3.DueDate = (DateTime.Now.AddDays(9)).ToString();

        j1.RushPriority = true;

        j1.Status = "Completed";
        j2.Status = "Accepted";  
        j3.Status = "Completed";

        JobItemList.Add(j1);
        JobItemList.Add(j2);
        JobItemList.Add(j3);
    }

    private void newJobBtn_Click(object sender, RoutedEventArgs e)
    {
        NewJobDialog newJobWindow = new NewJobDialog(workOrderCounter);

        newJobWindow.ShowDialog();

        if (newJobWindow.DialogResult == true)
        {
            if (newJobWindow.HasContent && newJobWindow.DialogResult.Value)
            {
                JobItemList.Add(newJobWindow.newJob);
                workOrderCounter++;

            }

        }

    }

    /*Formats each row in the data grid depending on how close the due date of each
     * job is.  Each color corresponds to how close the due date is from today.
     * Blue: Job is due in more than 7 days
     * Green: Job is due between 4-7 days
     * Yellow: Job is due in 0-3 days
     * Red:
     * */
    private void jobItemDataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
    {
        DateTime currentDate = DateTime.Now;
        DateTime dateValue = new DateTime();
        TimeSpan elapsed;
        Double daysLeft;
        Double enoughTime = 7;
        Double dueSoon = 3;
        Double dueToday = 0;


        foreach (JobItem item in jobItemDataGrid.ItemsSource)
        {

            var row = jobItemDataGrid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
            //subtracting the two dates to get an elapsed amount of days
            if ((DateTime.TryParse(item.DueDate.ToString(),out dateValue) == true))
            {

                //dateValue = DateTime.Parse(item.DueDate.ToString());
                elapsed = dateValue.Subtract(currentDate);
                daysLeft = elapsed.TotalDays;
                //MessageBox.Show("due date: " + dateValue.ToString() + " current date: " + currentDate.ToString() + " days left: " + daysLeft.ToString() + "rounded: "  + daysLeftRound.ToString());

                if (item.RushPriority == true)
                {
                    row.Background = new SolidColorBrush(Colors.Black);
                    row.Foreground = new SolidColorBrush(Colors.White);
                }
                else if (daysLeft > enoughTime)
                {
                    row.Background = new SolidColorBrush(Colors.Blue);
                    row.Foreground = new SolidColorBrush(Colors.White);
                }
                else if (daysLeft <= enoughTime && daysLeft > dueSoon)
                {
                    row.Background = new SolidColorBrush(Colors.Green);
                    row.Foreground = new SolidColorBrush(Colors.White);
                }
                else if (daysLeft <= dueSoon && daysLeft >= dueToday)
                {
                    row.Background = new SolidColorBrush(Colors.Yellow);
                }
                else if (daysLeft < dueToday)
                {
                    row.Background = new SolidColorBrush(Colors.Red);
                    row.Foreground = new SolidColorBrush(Colors.White);
                }

            }

        } 
    }

I when I add more than one dummy item from LoadDummies(), I get the error: "NullReferenceException was unhandled. Object reference not set to an instance of object."

All help is appreciated!

I think you forgot to create your JobItemList. try putting this in your constructor:

JobItemList = new List<JobItem>();

在下面的if语句中,添加一个空检入行

if ((DateTime.TryParse(item.DueDate.ToString(), out dateValue) == true) && row != null) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM