具有ShowUpDown控件的DateTimePicker不会随着月份增加

时间:2018-08-29 12:12:43

标签: c# winforms datetimepicker

我正在Windows窗体中使用标准DateTimePicker,其自定义格式为yyyyMM(日期不相关),并且ShowUpDown属性设置为true。

使用向上箭头增加月份可以使我从12增至1(12月至1月),但不会增加年份。 因此,我的DateTimePicker中的值从201812201801,而我希望它显示201901

1 个答案:

答案 0 :(得分:1)

AFAIK,没有任何开箱即用的功能可以实现此功能。因此,这是一种解决方法,虽然有点棘手,但可以使用:

private DateTime LastDate;
private void dtPicker_ValueChanged(object sender, EventArgs e)
{
    DateTime newDate = dtPicker.Value;
    if (newDate.Year == LastDate.Year)
    {
        if (LastDate.Month == 12 && newDate.Month == 1)
            dtPicker.Value = dtPicker.Value.AddYears(1);
        else if (LastDate.Month == 1 && newDate.Month == 12)
            dtPicker.Value = dtPicker.Value.AddYears(-1);
    }

    LastDate = dtPicker.Value;
}

由于您将ShowUpDown属性设置为true,因此用户将无法以任何其他方式更改该值。我唯一想到的缺点是,当您更改代码中的值时,例如,如果当前值为201812并尝试将其设置为201801,则会得到{{1 }}。为了防止这种情况的发生,您可以在更改值之前删除事件处理程序,然后在之后立即重新添加它:

201901