Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DatePicker System.FormatException

In this DatePicker if I type in an invalid date such as
1/1/20001 (enter key)
I get the following exception

A first chance exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: String was not recognized as a valid DateTime.

But it appears this is thrown by the binding and I cannot find a way to handle it.
In debug I get the above on the screen

Turned on stack trace and it says the error is thrown on SearchItem.Date1 get
But the problem is that get is not actually called in that situation

If I enter a valid date such as 1/1/2000 I see both the set and get called.

If I enter and invalid date there is no call to set.

Of I enter and invalid date and press enter or lost focus is just reverts back to the prior date and does not throw an exception. If the prior date was null it reverts to null.

Where this is a critical problem for me is if the user enters a valid date and then enters an invalid date the DatePicker just reverts to the last valid date. So the user is not aware the date did not change.

The question is how can I handle an invalid date exception?

<DatePicker Width="140" DisplayDateStart="1/1/1990" DisplayDateEnd="12/31/2020" 
            SelectedDate="{Binding Path=Date1, Mode=TwoWay, ValidatesOnExceptions=True, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"/>

If I take out

, ValidatesOnExceptions=True, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged  

nothing changes

private DateTime? date1; 
public DateTime? Date1
{
    get
    {
        try
        {
            return date1;
        }
        catch (Exception ex)
        {
            return (DateTime?)null;
            throw;
        }
    }
    set
    {
        if (date1 != value)
        {
            date1 = value;
            NotifyPropertyChanged("Date1");    
        }
    }
}
like image 369
paparazzo Avatar asked Dec 23 '14 18:12

paparazzo


1 Answers

One way I can think of is to use DateValidationError event:

XAML:

<DatePicker Width="140" DisplayDateStart="1/1/1990" DisplayDateEnd="12/31/2020" 
            SelectedDate="{Binding Path=Date1, Mode=TwoWay, 
            ValidatesOnExceptions=True, ValidatesOnDataErrors=True, 
            UpdateSourceTrigger=PropertyChanged}"
            DateValidationError="DatePicker_DateValidationError" />

Code behind:

private void DatePicker_DateValidationError(object sender, DatePickerDateValidationErrorEventArgs e)
{
    // throw FormatException
    e.ThrowException = true;

    //OR

    // handle the exception by showing message and clearing data
    MessageBox.Show(e.Exception.Message);
    ((DatePicker)sender).Text = null;
}
like image 51
Bahman_Aries Avatar answered Oct 23 '22 13:10

Bahman_Aries