Kirsty White
Kirsty White

Reputation: 1220

date difference using datepicker in wpf

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 in the first line :S

    private void button20_Click(object sender, RoutedEventArgs e)
    {
        DateTime start = datePicker1.DisplayDateStart.Value.Date;
        DateTime finish = datePicker2.DisplayDateStart.Value.Date;
        TimeSpan difference = start.Subtract(finish);
        textBlock10.Text = Convert.ToString(difference);
    }

Upvotes: 3

Views: 5574

Answers (2)

Dan J
Dan J

Reputation: 16708

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

Upvotes: 3

Anders Abel
Anders Abel

Reputation: 69260

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).

Upvotes: 1

Related Questions