1. 程式人生 > >C# DateTimePicker 預設值顯示為空

C# DateTimePicker 預設值顯示為空

#region  日期控制元件初始為空值處理

/// <summary>
/// 初始化日期時間控制元件
/// </summary>
/// <param name="dtp"></param>
public static void InitDateTimePicker(DateTimePicker dtp)
{
    dtp.Format = DateTimePickerFormat.Custom;
    dtp.CustomFormat = " ";  //必須設定成" "
    dtp.ValueChanged -= DateTimePicker_ValueChanged;
    dtp.ValueChanged += DateTimePicker_ValueChanged;
    dtp.KeyPress -= DateTimePicker_KeyPress;
    dtp.KeyPress += DateTimePicker_KeyPress;
}

public static void DateTimePicker_ValueChanged(object sender, EventArgs e)
{
    DateTimePicker dtp = (DateTimePicker)sender;                                 
    dtp.Format = DateTimePickerFormat.Long;
    dtp.CustomFormat = null; //null;
    dtp.Checked = false;// 解決BUG :防止日期控制元件不能選擇相同日期的 --- 要放置在設定格式之後
}

public static void DateTimePicker_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)8)  // backspace左刪除鍵
    {
        DateTimePicker dtp = (DateTimePicker)sender;
        dtp.Format = DateTimePickerFormat.Custom;
        dtp.CustomFormat = " ";
    }
}
#endregion