标签:
由于WinForm自带的DateTimePicker不能设置空值(Null),所以我基于原来的DateTimePicker做了扩展。
若有bug,可反馈,我再修改。
using System; using System.ComponentModel; using System.Windows.Forms; namespace WinFormTest { public class DateTimePicker2 : DateTimePicker { const string NullableFormat = " "; bool isSelfSetting; string originalCustomFormat; bool originalCustomFormatInitialized; DateTimePickerFormat? originalFormat; bool IsNullableState { get { return this.Format == DateTimePickerFormat.Custom && this.CustomFormat == NullableFormat; } } void SetNullable(bool nullable) { if (!this.originalFormat.HasValue) { this.originalFormat = this.Format; } if (!this.originalCustomFormatInitialized) { this.originalCustomFormat = this.CustomFormat; this.originalCustomFormatInitialized = true; } this.isSelfSetting = true; this.Format = nullable ? DateTimePickerFormat.Custom : this.originalFormat.Value; this.CustomFormat = nullable ? NullableFormat : this.originalCustomFormat; this.isSelfSetting = false; } #region Properties [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public DateTime? Value2 { get { return this.IsNullableState ? (DateTime?)null : Value; } set { if (value.HasValue) Value = value.Value; SetNullable(!value.HasValue); } } public new DateTimePickerFormat Format { get { return base.Format; } set { if (!this.isSelfSetting) this.originalFormat = value; base.Format = value; } } public new string CustomFormat { get { return base.CustomFormat; } set { if (!this.isSelfSetting) { this.originalCustomFormat = value; this.originalCustomFormatInitialized = true; } base.CustomFormat = value; } } #endregion #region Events protected override void OnGotFocus(EventArgs e) { if (this.IsNullableState) SetNullable(false); base.OnGotFocus(e); } protected override void OnMouseDown(MouseEventArgs e) { if (this.IsNullableState) SetNullable(false); base.OnMouseDown(e); } protected override void OnKeyDown(KeyEventArgs e) { SetNullable(e.KeyCode == Keys.Back || e.KeyCode == Keys.Delete); base.OnKeyDown(e); } #endregion } }
可设置空值(Nullable)的DateTimePicker
标签:
原文地址:http://www.cnblogs.com/csknife/p/4587248.html