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

DateTimePicker with ShowUpDown control doesn't increase year with months

我在 windows 表单中使用标准 DateTimePicker,自定义格式为 yyyyMM(日期不相关),ShowUpDown 属性 设置为是的。

使用向上箭头增加月份可以让我将它从 12 增加到 1(12 月到 1 月)但不会增加年份。 所以我的 DateTimePicker 中的值从 201812 变为 201801 而我希望它显示 201901.

据我所知,没有现成的方法可以实现此行为。所以,这里有一个解决方法,它有点笨拙但有效:

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,您将得到 201901 代替。为了防止这种情况发生,您可以在更改值之前删除事件处理程序,然后在之后重新添加它:

dtPicker.ValueChanged -= dtPicker_ValueChanged;
dtPicker.Value = new DateTime(2018, 1, 1);
dtPicker.ValueChanged += dtPicker_ValueChanged;