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

标签 .net datetimepicker null

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

最佳答案

这是 CodeProject 文章中关于创建 Nullable DateTimePicker 的一种方法。 .

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.



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

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 - 如何更改 .NET DateTimePicker 控件以允许输入空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/284364/

相关文章:

android - Tab Fragment错误中创建DatePicker和TimePicker

c# - Object.Equals(obj, null) 和 obj == null 有什么区别

c# - 如何处理来自 SQL Server 的 DBNull DateTime 字段?

c# - 丢失的线程会怎样?

c# - 如何在异步多线程爬虫中锁定回调类?

c# - MVC3 中的 Ninject 依赖注入(inject) - 在 Controller 之外

c# - 使用 WCF 使用 RESTful JSON API

C# DateTime解析问题

c++ - MFC CDateTimeCtrl 显示无

swift - 检查 Swift 字典扩展中的 nil 值