Friday, 16 December 2011

Nullable DateTimePicker control

In this blog I will show you how to modify DateTimePicker control to support data binding to Nullable dataset field. Usually when we want to bind a DateTimePicker to a Datetime field we use the following command:

   DateTimePicker1.DataBindings.Add(new Binding("Value", ds, customers.CustToOrders.OrderDate"));

The problem with this control is that : The Value  property is a DateTime  type and they cannot be assigned to null literal.

To workarround this problem I create my own DateTimePicker drived from the real one. and I override Value property using String as the new type. Because string can be assigned to null and can convert easily between string and DateTime types.

Here is the class:

    /// <summary>
    /// Summary description for DateTimePicker.
    /// </summary>

    public class DateTimePickerCustom : System.Windows.Forms.DateTimePicker
    {
        private DateTimePickerFormat oldFormat = DateTimePickerFormat.Long;
        private string oldCustomFormat = null;
        private bool bIsNull = false;


        public DateTimePickerCustom()
            : base()
        {
        }

        public new String Value
        {

            get
            {
                if (bIsNull)
                    return null;
                else
                    return base.Value.ToString("yyyy-MM-dd");
            }

            set
            {

                if ((value == null)  || (value == DBNull.Value.ToString()))
                {

                    if (!bIsNull)                    {
                        base.Value = base.MinDate;
                        oldFormat = this.Format;
                        oldCustomFormat = this.CustomFormat;
                        bIsNull = true;
                        this.Format = DateTimePickerFormat.Custom;
                        this.CustomFormat = " ";
                    }

                }
                else
                {
                    if (bIsNull)

                    {
                        this.Format = oldFormat;                       

                        this.CustomFormat = oldCustomFormat;
                    }
                    bIsNull = false;
                    base.Value = DateTime.Parse(value);
                }
            }
         }
     }
}