Wednesday, April 4, 2012

Display empty string in DateTimePicker

By default, WinForms DateTimePicker control displays current date. Depending on Format property of the DateTimePicker control, it can display long date and time(Format=Long), short date(Format=Short) or time only(Format=Time). And if the Format is set to Custom, various user defined format is possible.

When it comes to DateTimePicker, some people prefers to display empty string instead of current date/time when the form is first shown up. And the thing is DateTimePicker control does not allow you to enter empty string easily, since Value property of the control is DateTime type which does not allow null value. If it were DateTime? nullable type, displaying empty string would have been an easy task. Some developers make Nullable DateTimePicker control by inheriting it, but a workaround can be used by utilizing custom format.
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        // Setting CustomFormat to a Space.            
        dateTimePicker1.Format = DateTimePickerFormat.Custom;
        dateTimePicker1.CustomFormat = " ";            
    }
    private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
    {
        // Change Format to Long,Short or Time
        dateTimePicker1.Format = DateTimePickerFormat.Short;
        // add more
    }
}

To add empty string to DateTimePicker textbox, set Format to Custom and then assign empty string to CustomFormat property in form Load event handler or form constructor. Once user starts changing the DateTimePicker value, we reset the Format back to normal format such as Long, Short, Time.

2 comments:

  1. I just want to display something like "MM/DD/YYYY" tried
    dtpkToDate.Format = DateTimePickerFormat.Custom;
    dtpkToDate.CustomFormat = " MM/DD/YYYY";

    but gives output like "08/DD/YYYY"
    any clue
    Thank you!

    ReplyDelete
  2. gotcha dtpkToDate.CustomFormat = "'MM/DD/YYYY'";

    single qouts for string

    ReplyDelete