Sunday, August 15, 2004

Nullable Date Time Picker


A while back, i was so angry when i was using the .net c# dateTimePicker control on a winform. It did not support null dates. It defaulted to today's date. No matter if i push delete or anything.I decided to write a nullable one. I decided to write this one myself. Well, mostly myself.I got some ideas from usenet. Noone else had a solution that actually worked. I hope it works for you. BTW, in this control that inherits the date time picker, you must bind to BindMe, or else you will loose you null support.


using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;

namespace DateTimePickerNull
{
       public class DateTimePickerNull 
: System.Windows.Forms.DateTimePicker
       {

              public DateTimePickerNull()
              {
                     this.ShowCheckBox=true;
              }

              public object BindMe

              {
                     get
                     {
                            if (this.Checked)
                            {
                                   return base.Value;
                            }
                            else
                            {
                                   return System.DBNull.Value;
                            }
                     }
                     set
                     {
                            if (System.Convert.IsDBNull(value))
                            {       
                                   this.Checked=false;
                            }
                            else
                            {       
                                   if (this.Checked==false)
                                          this.Checked=true;

                                   this.Value = Convert.ToDateTime(value);
                            }
                     }
              }

       }
}