Subclassing DateTimePicker to support DBNull values
My table is designed to support Nulls in the datetime columns.
So I've subclassed the DateTimePicker and added the following code...
public new object Value
{
set
{
Type t = value.GetType();
if (t == typeof(DBNull))
{
base.Value = base.MinDate;
}
else
{
base.Value = (DateTime)value;
}
}
get
{
if (base.Value == base.MinDate)
return DBNull.Value;
else
return base.Value;
}
}
Which solves the basic problem by not storeing the DBNull, but storing the minimum value.
The next thing I need help with is how to format the Text to blank when it's the minimum value, plus to convert a blank back to DBNull on the way out.
To solve the exact same problem I took a bit of different approach. I wanted to leave the field as null if the user hadn't selected a date so I did this;
public class DBDateTimePicker:DateTimePicker
{
public DBDateTimePicker()
{
//
// TODO: Add constructor logic here
//
}
public object DBValue
{
get
{
if (this.Checked)
return base.Value;
else
return System.DBNull.Value;
}
set
{
if (System.Convert.IsDBNull(value))
this.Checked=false;
else
this.Value = Convert.ToDateTime(value);
}
}
}
Then I bind to “DBValue” (instead of Value) and it appears to work fine… if it is null, it is unchecked and disabled, otherwise it is enabled and can be set to any normal date value... if you uncheck the box yourself, then the data field is set to DBNull...