最简单且最健壮的修改.NET DateTimePicker控件,以允许用户输入null
值的方法是什么?
最简单且最健壮的修改.NET DateTimePicker控件,以允许用户输入null
值的方法是什么?
您无需修改它以实现此功能。
.NET 中的 DateTimePicker
实际上内置了一个复选框。
将 ShowCheckBox
属性设置为 true
。
然后,您可以使用 Checked
属性来查看用户是否已输入值。
http://msdn.microsoft.com/zh-cn/library/system.windows.forms.datetimepicker.showcheckbox(VS.80).aspx
以下是文章中自定义类组件的版本。我已经重写了
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;
}
}
}
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;
}
}