With the addition of Nullable Types to C# 2.0, I wrote my own NullableDateTimePicker control in very few lines of code, as opposed to the nullable DateTimePicker controls I've found that were written for C# 1.1.
csharp Code:
public partial class NullableDateTimePicker : DateTimePicker { private DateTime? dtNullable; public NullableDateTimePicker() { base.Format = DateTimePickerFormat.Custom; base.CustomFormat = " "; } public new DateTime? Value { get { if (dtNullable.HasValue) return base.Value; return null; } set { if (value == null) dtNullable = null; else dtNullable = base.Value = value.Value; OnValueChanged(EventArgs.Empty); } } protected override void OnValueChanged(EventArgs eventargs) { if (this.dtNullable.HasValue) { base.Format = DateTimePickerFormat.Short; } else { base.Format = DateTimePickerFormat.Custom; base.CustomFormat = " "; } base.OnValueChanged(eventargs); } protected override void OnCloseUp(EventArgs eventargs) { if (Control.MouseButtons == MouseButtons.None) { this.Value = base.Value; } base.OnCloseUp(eventargs); } }
Which is alright except if I bind the Value property and the binding source returns a DBNull.Value then I get the following error:
error Code:
Invalid cast from 'System.DateTime' to 'System.Nullable`
How can I represent a DateTime so that it may contain a valid DateTime, and instead of null, DBNull.Value?




Reply With Quote