Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...