date difference using datepicker in wpf

后端 未结 2 1100
死守一世寂寞
死守一世寂寞 2020-12-21 09:29

Im trying to calculate the how many days there are between two dates and display the result in a textblock, i am using wpf. However i get a nullable object must have a value

相关标签:
2条回答
  • 2020-12-21 09:54

    As the error message implies, DisplayDateStart is a nullable property, which means it can (and, by default, does) have no value. You have to handle this condition to produce sensible results.

    That said, the DisplayDateStart property refers to the earliest date shown in the DatePicker's calendar, not the date the user has picked: for that, you need the SelectedDate property, which is also nullable.

    There are a variety of ways you could handle a NULL value: display nothing in the TextBlock, display "N/A" or some other default, etc. Here's an example:

    private void button20_Click(object sender, RoutedEventArgs e)
    {
        // This block sets the TextBlock to a sensible default if dates haven't been picked
        if(!datePicker1.SelectedDate.HasValue || !datePicker2.SelectedDate.HasValue)
        {
            textBlock10.Text = "Select dates";
            return;
        }
    
        // Because the nullable SelectedDate properties must have a value to reach this point, 
        // we can safely reference them - otherwise, these statements throw, as you've discovered.
        DateTime start = datePicker1.SelectedDate.Value.Date;
        DateTime finish = datePicker2.SelectedDate.Value.Date;
        TimeSpan difference = finish.Subtract(start);
        textBlock10.Text = difference.TotalDays.ToString();
    }
    
    0 讨论(0)
  • 2020-12-21 10:07

    If you want to get the selected date, you're using the wrong property. DisplayDateStart and DisplayDateEnd limits the possible choices. They are nullable because it should be possible to create a date picker without any limitations. Change your start and finish assignments to use the DisplayDate property instead:

    DateTime start = datePicker1.DisplayDate.Date;
    DateTime finish = datePicker2.DisplayDate.Date;
    

    You should also consider renaming your datepickers. Having controls named datePicker1 and datePicker2 is typically hard to remember. What about datePickerStart and datePickerEnd?

    (Disclaimer: I know that WPF controls typically don't get a name, because they are databound so the name won't matter, but in this case they are explicitly accessed and should have proper names).

    0 讨论(0)
提交回复
热议问题