且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将 win 表单日期时间选择器设置为没有默认值?

更新时间:2022-05-23 03:09:20

您不能拥有带有开箱即用控件的毫无价值的日期选择器.为什么?它由不可为空的 DateTime 支持.

You can't have a valueless datepicker with the out-of-the-box control. Why? It is backed by DateTime, which is non-nullable.

您可以使用另一个控件禁用它,或者在用户单击之前禁用它(对于像我这样的键盘爱好者来说糟糕的 UX),或者找到或创建(!)一个使用 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.

  • 使用字段或私有属性来保存from"和to"日期,而不是从 dtp 中读取它们,并将它们的默认值设置为 min 和 max
  • 使用布尔标志来指示您何时在代码中操作 dtp 值,并在 dtp 的 ValueChanged 事件中,将标志的值设置为 false
  • 在表单加载事件中,将标志设置为 true 并将 dtp 值设置为今天的日期
  • 也在 ValueChanged 事件中,将 fromto 字段设置为 dtps 的值(当dtp 更改,因为用户会看到另一个设置为今天,但搜索值仍将是 min 或 max).
  • use fields or private properties to hold the 'from' and 'to' dates, instead of reading them from the dtp, and set their defaults to min and max
  • use a boolean flag to indicate when you are manipulating the dtp value in code, and in the dtp's ValueChanged event, set the flag's value to false
  • in the form load event, set the flag to true and dtp value to today's date
  • also in the ValueChanged 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.

我认为对您来说***的解决方案是设置一个按日期范围搜索"复选框.它要么启用两个被禁用的 dtps,要么显示否则隐藏的 dtps.然后你从最小值到最大值搜索,除非复选框被选中,当复选框选中时,你使用两个 dtp 日期,无论它们是什么.不要忘记处理 tofrom 乱序的情况,这可以通过多种方式完成.

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.