How to alter a .NET DateTimePicker control to allow enter null values?(如何更改 .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 控件以允许输入空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何更改 .NET DateTimePicker 控件以允许输入空值?


- 带问号的 nvarchar 列结果 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 使用 rss + c# 2022-01-01