views:

2012

answers:

3

I would like to be able to display a DateTimePicker that has a default value of nothing, i.e. no date.

For example, I have a start date dtTaskStart and an end date dtTaskEnd for a task, but the end date is not known, and not populated initially.

I have specified a custom format of yyyy-MM-dd for both controls.

Setting the value to null, or an empty string at runtime causes an error, so how can I accomplish this?

I have considered using a checkbox to control the enabling of this field, but there is still the issue of displaying an initial value..

Edit:
Arguably a duplicate of the question DateTimePicker Null Value (.NET), but the solution I found for my problem is not a solution for that question, so I think it should remain here for others to find..

A: 

Obfuscating the value by using the CustomFormat property, using checkbox cbEnableEndDate as the flag to indicate whether other code should ignore the value:

    If dateTaskEnd > Date.FromOADate(0) Then
        dtTaskEnd.Format = DateTimePickerFormat.Custom
        dtTaskEnd.CustomFormat = "yyyy-MM-dd"
        dtTaskEnd.Value = dateTaskEnd 
        dtTaskEnd.Enabled = True
        cbEnableEndDate.Checked = True
    Else
        dtTaskEnd.Format = DateTimePickerFormat.Custom
        dtTaskEnd.CustomFormat = " "
        dtTaskEnd.Value = Date.FromOADate(0)
        dtTaskEnd.Enabled = False
        cbEnableEndDate.Checked = False
    End If
brass-kazoo
Tricksy/hacky but effective. :)
AR
+1  A: 

This thread answers the question how to enter NULL value into DateTimePicker. http://stackoverflow.com/questions/284364/datetimepicker-null-value-net

Thanks.. I'm not sure why I dind't come across this in my search.
brass-kazoo
+1  A: 

this worked for me for c#

if (enableEndDateCheckBox.Checked == true)
        {
            endDateDateTimePicker.Enabled = true;
            endDateDateTimePicker.Format = DateTimePickerFormat.Short;                
        }
        else
        {
            endDateDateTimePicker.Enabled = false;
            endDateDateTimePicker.Format = DateTimePickerFormat.Custom;
            endDateDateTimePicker.CustomFormat = " ";
        }

nice one guys!

David Swindells