更改.NET DateTimePicker控件以允许用户输入null
值的最简单,最可靠的方法是什么?
这是此CodeProject文章中有关创建Nullable DateTimePicker的一种方法。
我重写了
Value
属性,以将Null
值接受为DateTime.MinValue
,同时保持标准控件的MinValue
和MaxValue
的有效性。
这里是文章中的自定义类组件的版本
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
实际上具有内置的复选框。
将ShowCheckBox
属性设置为true
。
然后您可以使用Checked
属性查看用户是否输入了值。
http://msdn.microsoft.com/en-us/library/system.windows.forms.datetimepicker.showcheckbox(VS.80).aspx
放置一个标有“启用通知”之类的附加复选框,以启用/禁用DateTimePicker。
[Tri的解决方案对我来说还不是很有效,所以以为Grazioli先生和他做了一些事情:http://www.codeguru.com/csharp/csharp/cs_controls/custom/article.php/c9645
我在解决方案上走了很长一段路,在代码注释中有一些关于此控件特有问题的发现:
将ShowCheckBox属性设置为true。然后,您可以使用Checked属性,如下所示:
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
DateTimePicker thisDateTimePicker = (DateTimePicker)sender;
if (thisDateTimePicker.Checked == false)
{
thisDateTimePicker.CustomFormat = @" "; //space
thisDateTimePicker.Format = DateTimePickerFormat.Custom;
}
else
{
thisDateTimePicker.Format = DateTimePickerFormat.Short;
}
}