I have an object that I'm trying to bind its properties to two DateTimePicker controls.
class Order { public DateTime OrderPlacedDate { get; } public Nullable<DateTime> ShippedDate { get; } }
What is the proper way to bind Nullable DateTime Property to DateTimePicker?
There's not really a right way since the DateTimePicker does not have good support for null values. You have a couple of options:
1. You can use a ReadOnly TextBox and a MonthCalendar rather than a DateTimePicker. You'd bind to the TextBox and use the MonthCalendar to set the date in the TextBox.
2. You can use DateTimePicker's null support which is a little clumsy from a UI perspective. This also requires you to write some glue code that maps the DateTimePicker's null representation to a null on your Nullable<DateTime> property. You can do this as follows:
Customer _customer; // Has a Nullable<DateTime> property called "HireDate" private void Form1_Load(object sender, EventArgs e) { // Create Customer _customer = new Customer("555", "John Doe", 1000, DateTime.Now); // Bind Binding binding = new Binding("Value", _customer, "HireDate", true); this.dateTimePicker1.DataBindings.Add(binding); // BindingComplete binding.Format += new ConvertEventHandler(Binding_Format); binding.Parse += new ConvertEventHandler(Binding_Parse); } void Binding_Parse(object sender, ConvertEventArgs e) { // Need to make the Control show NULL Binding binding = sender as Binding; if (null != binding) { DateTimePicker dtp = (binding.Control as DateTimePicker); if ((null != dtp) && (dtp.Checked)) e.Value = new Nullable<DateTime>(); } } void Binding_Format(object sender, ConvertEventArgs e) { INullableValue inv = (e.Value as INullableValue); if ((null != inv) && (!inv.HasValue)) { // Need to make the Control show NULL Binding binding = sender as Binding; if (null != binding) { DateTimePicker dtp = (binding.Control as DateTimePicker); if (null != dtp) { dtp.ShowCheckBox = true; dtp.Checked = false; e.Value = dtp.Value; } } } }