Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Null value in DateTimePicker in C#

Tags:

c#

winforms

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

like image 618
Kiran Avatar asked Dec 20 '22 10:12

Kiran


1 Answers

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= " ";
like image 154
MethodMan Avatar answered Dec 22 '22 22:12

MethodMan