本文介紹了如何更改 .NET DateTimePicker 控件以允許輸入空值?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
更改 .NET DateTimePicker 控件以允許用戶輸入 null
值的最簡單、最可靠的方法是什么?
What's the easiest and most robust way of altering the .NET DateTimePicker control, to allow users to enter null
values?
推薦答案
這是 CodeProject 文章中關于創建 可以為空的 DateTimePicker.
Here's an approach from this CodeProject article on creating a Nullable DateTimePicker.
我已覆蓋 Value
屬性以接受 Null
值作為 DateTime.MinValue
,同時保持 MinValue
的驗證標準控件的code>和MaxValue
.
I have overridden the
Value
property to acceptNull
value asDateTime.MinValue
, while maintaining the validation ofMinValue
andMaxValue
of the standard control.
這是文章中自定義類組件的一個版本
Here's a version of the custom class component from the article
public class NullableDateTimePicker : System.Windows.Forms.DateTimePicker
{
private DateTimePickerFormat originalFormat = DateTimePickerFormat.Short;
private string originalCustomFormat;
private bool isNull;
public new DateTime Value
{
get => isNull ? DateTime.MinValue : base.Value;
set
{
// incoming value is set to min date
if (value == DateTime.MinValue)
{
// if set to min and not previously null, preserve original formatting
if (!isNull)
{
originalFormat = this.Format;
originalCustomFormat = this.CustomFormat;
isNull = true;
}
this.Format = DateTimePickerFormat.Custom;
this.CustomFormat = " ";
}
else // incoming value is real date
{
// if set to real date and previously null, restore original formatting
if (isNull)
{
this.Format = originalFormat;
this.CustomFormat = originalCustomFormat;
isNull = false;
}
base.Value = value;
}
}
}
protected override void OnCloseUp(EventArgs eventargs)
{
// on keyboard close, restore format
if (Control.MouseButtons == MouseButtons.None)
{
if (isNull)
{
this.Format = originalFormat;
this.CustomFormat = originalCustomFormat;
isNull = false;
}
}
base.OnCloseUp(eventargs);
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
// on delete key press, set to min value (null)
if (e.KeyCode == Keys.Delete)
{
this.Value = DateTime.MinValue;
}
}
}
這篇關于如何更改 .NET DateTimePicker 控件以允許輸入空值?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!