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

猜你喜欢

转载自blog.csdn.net/qq_35106907/article/details/84318004