using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.ComponentModel; public class DateTimePickerA : DateTimePicker { public DateTimePickerA() : base() { SetNullText(); base.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold); } /// /// 值是否已改变 /// private bool IsValueChanged = false; /// /// 原格式字符串 /// private string _formatString = "yyyy年MM月dd日"; /// /// 原格式 /// private DateTimePickerFormat _originalFormat = DateTimePickerFormat.Custom; /// /// 可空日期 /// private DateTime? valueX = null; /// /// 日期(值改变前为null) /// [Browsable(true), Category("扩展属性"), Description("可空日期(值改变前为null)")] public DateTime? ValueX { get { return valueX; } set { if (value == null) { valueX = value; SetNullText(); } else { this.CustomFormat = FormatString; this.Value = value.Value; valueX = value; } } } /// /// 格式字符串 /// [Browsable(true), Category("扩展属性"), Description("格式字符串")] public string FormatString { get { return _formatString; } set { _formatString = value; } } /// /// 设置格式 /// [Browsable(true), Category("扩展属性"), Description("设置格式")] public DateTimePickerFormat OriginalFormat { get { return _originalFormat; } set { _originalFormat = value; } } /// /// 开始时间(该日期的00:00:00) /// [Browsable(true), Category("扩展属性"), Description("开始时间(为当前选中日期的00:00:00)")] public DateTime? BeginTime { get { if (ValueX.HasValue) return DateTime.Parse(ValueX.Value.ToString("yyyy-MM-dd 00:00:00")); else return null; } } /// /// 结束时间(该日期的23:59:59) /// [Browsable(true), Category("扩展属性"), Description("结束时间(为当前选中日期的23:59:59)")] public DateTime? EndTime { get { if (ValueX.HasValue) { return DateTime.Parse(ValueX.Value.ToString("yyyy-MM-dd 23:59:59")); } else return null; } } /// /// 设置空字符显示 /// private void SetNullText() { this.Format = System.Windows.Forms.DateTimePickerFormat.Custom; this.CustomFormat = " "; } protected override void OnCloseUp(EventArgs eventargs) { if (IsValueChanged) { this.Format = _originalFormat; this.CustomFormat = _formatString; valueX = this.Value; IsValueChanged = false; } base.OnCloseUp(eventargs); } protected override void OnValueChanged(EventArgs eventargs) { this.IsValueChanged = true; base.OnValueChanged(eventargs); } protected override void OnKeyDown(KeyEventArgs e) { //删除时间 www.2cto.com if (e.KeyCode == Keys.Back || e.KeyCode == Keys.Delete) { this.ValueX = null; this.CustomFormat = " "; } base.OnKeyDown(e); } }