I am implementing search functionality in WinForms and I search by date range. Thus there are dateForm and dateTo date pickers on the form. By default their values are date
The DateTimePicker has a ShowCheckBox property that "Determines whether a check box is displayed in the control. When the box is unchecked, no value is selected."
I've used something like the following for date range selectors that can be empty. One user told me that at first, she didn't know what the check box was for, but she figured it out on her own after using it a couple of times.
public DateTime? EndDate
{
get
{
DateTime? returnValue = null;
if (endDateDateTimePicker.Checked)
{
returnValue = endDateDateTimePicker.Value;
}
return returnValue;
}
set
{
if (value.HasValue)
{
endDateDateTimePicker.Checked = true;
endDateDateTimePicker.Value = value.Value;
}
else
{
endDateDateTimePicker.Checked = false;
}
}
}
You can't have a valueless datepicker with the out-of-the-box control. Why? It is backed by DateTime, which is non-nullable.
You can disable it with another control, or leave it disabled until the user clicks (bad UX for keyboard enthusiasts, like myself), or find or create (!) one that uses Nullable<DateTime>
.
In response to your comment, yes, you can do this; in fact, I've done it.
ValueChanged
event, set the flag's value to falseValueChanged
event, set the from
and to
fields to the values of the dtps (you have to set both when either dtp changes, because the user will see the other one as set to today, but the search value will still be min or max).The problems with this is that once the user has changed the date selection, she can't easily go back to "all dates." Furthermore, the user can't select "today only" without first changing one of the dates and then changing it back.
I think the best solution for you is to have a checkbox, "search by date range," which either enables the two dtps that are otherwise disabled, or displays the dtps that are otherwise hidden. Then you search from min to max unless the checkbox is checked, and when the checkbox is checked, you use the two dtp dates no matter what they are. Don't forget to deal with to
and from
being out of order, which can be done in several ways.
You can set DateDateTimePicker.Format
property to Custom
.
Then set DateDateTimePicker.CustomFormat
property to your default text (e.g "N/A"
or a space " "
)
After the user has selected a certain date value, you should set back the format property to short etc.
Hope this helps!
Have a look here for a nullable datetimepicker on CodeProject, in fact there are a few here.
Put a check box next to each datetime picker, and use the check box to enable/disable the datetime picker.
So if the datetimepicker is disabled, you know the user do not want to specify the datetime.