使DateTimePicker仅在WinForms中用作TimePicker


83

如何限制DateTimePicker仅选择时间?我不知道如何禁用当您按下右侧的按钮时会掉落的日历控件DateTimePicker

Answers:


139

MSDN的摘录:

“以下代码示例显示了如何创建一个DateTimePicker,使用户只能选择一个时间。”

timePicker = new DateTimePicker();
timePicker.Format = DateTimePickerFormat.Time;
timePicker.ShowUpDown = true;

9
哈,解决方案很简单:只需将datetimepicker的ShowUpDown属性设置为true,并将Format设置为DateTimePickerFormat.Time。仅将Format设置为DateTimePickerFormat.Time是不够的。
Blablablaster

41

...或者如果您只想显示时间值的一部分,请使用“自定义”:

timePicker = new DateTimePicker();
timePicker.Format = DateTimePickerFormat.Custom;
timePicker.CustomFormat = "HH:mm"; // Only use hours and minutes
timePicker.ShowUpDown = true;

5
如果使用此路由,并且需要指定AM或PM,则可以将其添加tt到字符串中。的格式选项全部列表在这里:msdn.microsoft.com/en-us/library/...
AdamMc331

14

您想要将其“格式”属性设置为时间,并向其添加一个旋转按钮控件:

yourDateTimeControl.Format = DateTimePickerFormat.Time;
yourDateTimeControl.ShowUpDown = true;

2

如果要通过属性来执行此操作,可以通过将to的Format属性和property设置为 DateTimePicker来实现。另外,可以在属性中设置。DateTimePickerFormat.TimeShowUpDowntruecustomFormat


1

最好的方法是这样的:

datetimepicker.Format = DatetimePickerFormat.Custom;
datetimepicker.CustomFormat = "HH:mm tt";
datetimepicker.ShowUpDowm = true;

我喜欢您将“ tt”添加到自定义格式的方式,因此我们可以选择AM或PM
Jamisco

-2

将以下事件添加到DateTimePicker

Private Sub DateTimePicker1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles DateTimePicker1.KeyPress
    e.Handled = True
End Sub

2
这种语言肯定看起来不像C#。另外,您应该解释该代码的作用。它如何禁用日期更改,但保留时间更改。
David FerenczyRogožan2016年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.