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 dtTaskStar
Better to use text box for calling/displaying date and while saving use DateTimePicker. Make visible property true or false as per requirement.
For eg : During form load make Load date in Textbox and make DTPIcker invisible and while adding vice versa
Just set the property as follows:
When the user press "clear button" or "delete key" do
dtpData.CustomFormat = " " 'An empty SPACE
dtpData.Format = DateTimePickerFormat.Custom
On DateTimePicker1_ValueChanged
event do
dtpData.CustomFormat = "dd/MM/yyyy hh:mm:ss"
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!
Listen , Make Following changes in your code if you want to show empty datetimepicker and get null when no date is selected by user, else save date.
if user will interact with datetimepicker its VALUECHANGED event will be called and there set its TAG property to 1.
Now when saving, check if its TAG is zero, then save NULL date else if TAG is 1 then pick and save Datetime picker value.
It Works like a charm.
Now if you want its value be changed back to empty by user interaction, then add checkbox and show text "Clear" with this checkbox. if user wants to clear date, simply again set its CUSTOM FORMAT property to empty string " ", and set its TAG back to 0. Thats it..
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
When I want to display an empty date value I do this
if (sStrDate != "")
{
dateCreated.Value = DateTime.Parse(sStrDate);
}
else
{
dateCreated.CustomFormat = " ";
dateCreated.Format = DateTimePickerFormat.Custom;
}
Then when the user clicks on the control I have this:
private void dateControl_MouseDown(object sender, MouseEventArgs e)
{
((DateTimePicker)sender).Format = DateTimePickerFormat.Long;
}
This allows you to display and use an empty date value, but still allow the user to be able to change the date to something when they wish.
Keep in mind that sStrDate has already been validated as a valid date string.