【问题标题】:DateTimePicker with ShowUpDown control doesn't increase year with months带有 ShowUpDown 控件的 DateTimePicker 不会随月份增加年份
【发布时间】:2018-08-29 12:12:43
【问题描述】:

我在 Windows 窗体中使用标准 DateTimePicker,自定义格式为 yyyyMM(与日期无关),ShowUpDown 属性设置为 true。

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

【问题讨论】:

    标签: c# winforms datetimepicker


    【解决方案1】:

    AFAIK,没有什么开箱即用的方法可以实现这种行为。所以,这里有一个解决方法,它有点 hacky 但它有效:

    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;
    

    【讨论】:

    • 这非常有效。如果在接下来的一个小时左右没有其他人能做得更好,我会将其标记为我接受的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2016-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多