[英]C# DatePicker Validating Date
DatePicker allows selecting a date. DatePicker允许选择日期。
UPDATE: I would like to force DatePicker to allow only entry as dd/mm/yyyy. 更新:我想强制DatePicker只允许输入dd / mm / yyyy。 So, if user tries to enter "December 21, 2015" it would not allow it. 因此,如果用户尝试输入“ 2015年12月21日”,则不允许输入。
I am in .NET Framework 4.5 我在.NET Framework 4.5中
To catch cases where the text typed into the DatePicker is not a valid date format you should handle the DateValidationError
event . 要捕获在DatePicker中键入的文本不是有效日期格式的情况,应处理DateValidationError
事件 。 You'll get passed a System.FormatException
if the format isn't acceptable. 如果格式不可接受,您将通过System.FormatException
。
To limit the drop-down Calendar to the current year you can set the DisplayDateStart
and DisplayDateEnd
properties - but that doesn't stop you typing other dates in the text box. 要将下拉日历限制为当前年份,可以设置DisplayDateStart
和DisplayDateEnd
属性-但这不会阻止您在文本框中键入其他日期。
MyDatePicker.DisplayDateStart = new DateTime(DateTime.Now.Year, 1, 1);
MyDatePicker.DisplayDateEnd = new DateTime(DateTime.Now.Year, 12, 31);
To limit the DatePicker to the current year set the BlackoutDates
property to exclude all dates other than the current year. 要将DatePicker限制为当前年份,请将BlackoutDates
属性设置为排除当前年份以外的所有日期。 For example: 例如:
// Exclude all dates before the start of this year
MyDatePicker.BlackoutDates.Add(
new CalendarDateRange(DateTime.MinValue, new DateTime(DateTime.Now.Year - 1, 12, 31)));
// Exclude all dates after the end of this year
MyDatePicker.BlackoutDates.Add(
new CalendarDateRange(new DateTime(DateTime.Now.Year + 1, 1, 1), DateTime.MaxValue));
A validly formatted date that falls into one of the blackout date ranges will cause an ArgumentOutOfRangeException to be passed to the DateValidationError event handler 有效格式的日期落入停电日期范围之一,将导致ArgumentOutOfRangeException传递给DateValidationError事件处理程序
Use the following code: 使用以下代码:
DateTimePicker.Format = DateTimePickerFormat.Custom
DateTimePicker.CustomFormat = "dd-MM-yyyy"
Try this to validate the date range starting from today to 30 more days. 尝试此操作以验证日期范围,从今天到30天。
System.DateTime today = System.DateTime.Today;
this.DateTimePicker.MinDate = new System.DateTime(today.Year, today.Month, today.Day);
this.DateTimePicker.MaxDate = today.AddDays(30);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.