更改 .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 控件以允许输入空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!