I'm trying to get a DateTimePicker object to populate with the default text (Select a date) when it doesn't get any date back from the database. If there is a date in the database, the field will populate with that date.
I wroting code that has a two way bind on SelectedDate option to a DateTime property on in the code-behind. It works properly and populates the field with 01/01/0001 since that is the null of DateTime objects. I've tried to changing it to a OneWayToSource and just bind the date if it is greater than 01/01/0001 but it puts a redbox around the object if it doesn't get a date.
Any suggestion?
Thanks for the help everyone! Here is the solution that I found.
[ValueConversion(typeof(DateTime), typeof(DateTime))]
class DateTimeNullConverter: IValueConverter
{
public object Convert (object value, Type targetType, object parameter, Culture culture)
{
if (value != null)
{
DateTime dateTime = (DateTime)value;
if (dateTime.Year.ToString == "1")
return null;
else
return dateTime;
}
else
{
return null;
}
}
public object ConvertBack (object value, Type targetType, object parameter, Culture culture)
{
DateTime convertDateTime;
if (value == null)
{
convertDateTime = new DateTime();
}
else
{
convertDateTime = (DateTime) value;
}
return convertDateTime;
}
}