Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set DateTimePicker value to be null

I am developing a WinForms UI with two DateTimePicker controls. Initially I want to set the value of the controls to null until a user selects a date. If the user does not select a date, it will pass a value of null to the database.

By default it takes the current date.

Could you plz suggest something or attach a piece of code which will help me out.

I have tried setting the MinDate property but it doesn't work.

The code is in C# .Net.

Thanks, Manali.

like image 655
Manali Avatar asked May 10 '11 09:05

Manali


People also ask

How do you make a DatePicker empty?

You just need to set property valueDefault={null} and the DatePicker will be blank.

How can I make a DateTimePicker display an empty string?

Set datetimepicker FORMAT property to custom. set CUSTOM FORMAT property to empty string " ". set its TAG to 0 by default.

How check DatePicker is null?

The DatePicker class has a property, SelectedDate, which enable you to get or set the selected date. If there is none selected, it means its value will be null.


2 Answers

I think the best solution is to use the build-in checkbox that tell the user if a value is specified or not.

Set the control property ShowCheckBox = true

When you bind the value to it do something like

 if (value == DateTime.MinValue) {
    datePicker.Checked = false;
  } else {
    datePicker.Checked = true;
    datePicker.Value = value;
  }

When reading back the value check the Checked property.

If you don't like the displayed value when it's unchecked, you can combine that with the other suggestions.

  if (!datePicker.Checked) {
    // hide date value since it's not set
    datePicker.CustomFormat = " ";
    datePicker.Format = DateTimePickerFormat.Custom;
  } else {
    datePicker.CustomFormat = null;
    datePicker.Format = DateTimePickerFormat.Long; // set the date format you want.
  }
like image 100
Zyo Avatar answered Sep 18 '22 17:09

Zyo


I know this is an older post, but others might still find this useful. It is fairly elegant and concise. I used this with a .Net 4.0 DateTimePicker but earlier versions should work with minimal tweaking. It leverages MinDate and Checked.

    // 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; 
like image 30
K Kimble Avatar answered Sep 18 '22 17:09

K Kimble