Set DateTimePicker value to be null

前端 未结 8 1090
感情败类
感情败类 2020-12-01 16:43

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 us

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 17:23

    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.
      }
    

提交回复
热议问题