如何更改 .NET DateTimePicker 控件以允许输入空值?

时间:2022-12-31
本文介绍了如何更改 .NET DateTimePicker 控件以允许输入空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更改 .NET DateTimePicker 控件以允许用户输入 null 值的最简单、最可靠的方法是什么?

What's the easiest and most robust way of altering the .NET DateTimePicker control, to allow users to enter null values?

推荐答案

这是 CodeProject 文章中关于创建 可以为空的 DateTimePicker.

Here's an approach from this CodeProject article on creating a Nullable DateTimePicker.

我已覆盖 Value 属性以接受 Null 值作为 DateTime.MinValue,同时保持 MinValue 的验证标准控件的code>和MaxValue.

I have overridden the Value property to accept Null value as DateTime.MinValue, while maintaining the validation of MinValue and MaxValue of the standard control.

这是文章中自定义类组件的一个版本

Here's a version of the custom class component from the article

public class NullableDateTimePicker : System.Windows.Forms.DateTimePicker
{
    private DateTimePickerFormat originalFormat = DateTimePickerFormat.Short;
    private string originalCustomFormat;
    private bool isNull;

    public new DateTime Value
    {
        get => isNull ? DateTime.MinValue : base.Value;
        set
        {
            // incoming value is set to min date
            if (value == DateTime.MinValue)
            {
                // if set to min and not previously null, preserve original formatting
                if (!isNull)
                {
                    originalFormat = this.Format;
                    originalCustomFormat = this.CustomFormat;
                    isNull = true;
                }

                this.Format = DateTimePickerFormat.Custom;
                this.CustomFormat = " ";
            }
            else // incoming value is real date
            {
                // if set to real date and previously null, restore original formatting
                if (isNull)
                {
                    this.Format = originalFormat;
                    this.CustomFormat = originalCustomFormat;
                    isNull = false;
                }

                base.Value = value;
            }
        }
    }

    protected override void OnCloseUp(EventArgs eventargs)
    {
        // on keyboard close, restore format
        if (Control.MouseButtons == MouseButtons.None)
        {
            if (isNull)
            {
                this.Format = originalFormat;
                this.CustomFormat = originalCustomFormat;
                isNull = false;
            }
        }
        base.OnCloseUp(eventargs);
    }

    protected override void OnKeyDown(KeyEventArgs e)
    {
        base.OnKeyDown(e);

        // on delete key press, set to min value (null)
        if (e.KeyCode == Keys.Delete)
        {
            this.Value = DateTime.MinValue;
        }
    }
}

这篇关于如何更改 .NET DateTimePicker 控件以允许输入空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:检查空值的最短方法,如果不是,则分配另一个 下一篇:如何使用 .NET XmlSerializer 使值类型可以为空?

相关文章

最新文章