Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
470 views
in Technique[技术] by (71.8m points)

c# - 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);
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...