[csharp]
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;
namespace WindowsFormsApplication1.Common
{
/// <summary>
/// 描述:可空值的DateTimePicker控件 v1.2
/// 作者:李偉波
/// 創建日期:2010-01-16
/// 修改日期:2012-07-17 修改賦值後不顯示時間的BUG、刪除時間後再打開面板未選擇時間也賦值的問題。
/// </summary>
public class DateTimePickerX : DateTimePicker
{
public DateTimePickerX()
: base()
{
SetNullText();
}
/// <summary>
/// 值是否已改變
/// </summary>
private bool IsValueChanged = false;
/// <summary>
/// 原格式字符串
/// </summary>
private string _formatString = "yyyy年MM月dd日";
/// <summary>
/// 原格式
/// </summary>
private DateTimePickerFormat _originalFormat = DateTimePickerFormat.Custom;
/// <summary>
/// 可空日期
/// </summary>
private DateTime? valueX = null;
/// <summary>
/// 日期(值改變前為null)
/// </summary>
[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;
}
}
}
/// <summary>
/// 格式字符串
/// </summary>
[Browsable(true), Category("擴展屬性"), Description("格式字符串")]
public string FormatString
{
get { return _formatString; }
set { _formatString = value; }
}
/// <summary>
/// 設置格式
/// </summary>
[Browsable(true), Category("擴展屬性"), Description("設置格式")]
public DateTimePickerFormat OriginalFormat
{
get { return _originalFormat; }
set { _originalFormat = value; }
}
/// <summary>
/// 開始時間(該日期的00:00:00)
/// </summary>
[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;
}
}
/// <summary>
/// 結束時間(該日期的23:59:59)
/// </summary>
[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;
}
}
/// <summary>
/// 設置空字符顯示
/// </summary>
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);
}
}
}
作者:ranbolwb