I am developing a winform
based Desktop application in C#. I would like the user to set the DateTimePicker to Null
. I am developing a search box, and would like to ignore the date if it is set to Null
Here is what I am doing :
this.dateTimePicker2.CustomFormat = " ";
this.dateTimePicker2.Format = DateTimePickerFormat.Custom;
private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
{
this.dateTimePicker2.CustomFormat = "dd-MM-yy";
}
So far so good. However, once the user selects the date, the dateTimePicker2
control shows some date ( the date the user has selected). There is no way to set the date to null again. I am not keen to enable the checkbox associated with the datetimepicker
control.
I was wondering if it is possible to set the datetimepicker
date to null
.
Thanks
This is in reference from a post that is old but other users on this site have posted it here you go
// Use ValueChanged to decide if the value should be displayed:
dateTimePicker1.ValueChanged += (s, e) => { dateTimePicker1.CustomFormat = (dateTimePicker1.Checked && dateTimePicker1.Value != dateTimePicker1.MinDate) ? "MM/dd/yyyy" : " "; };
//When getting the value back out, use something like the following:
DateTime? dt = (dateTimePicker1.Checked && dateTimePicker1.Value != dateTimePicker1.MinDate) ? (DateTime?) dateTimePicker1.Value : null;
// or
DateTime dt2 = (dateTimePicker1.Checked && dateTimePicker1.Value != dateTimePicker1.MinDate) ? dateTimePicker1.Value : DateTime.MinValue;
or you can set the CustomFormat to " " an empty space like the following below
dateTimePicker1.CustomFormat= " ";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With