在 C# 中的 DateTimePicker 中设置空值 [英] Set Null value in DateTimePicker in C#

查看:34
本文介绍了在 C# 中的 DateTimePicker 中设置空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 C# 开发一个基于 winform 的桌面应用程序.我希望用户将 DateTimePicker 设置为 Null.我正在开发一个搜索框,如果日期设置为 Null

I am developing a winform based Desktop application in C#. I would like the user to set the DateTimePicker to Null. I am developing a search box, and would like to ignore the date if it is set to Null

这是我在做什么:

     this.dateTimePicker2.CustomFormat = " ";
     this.dateTimePicker2.Format = DateTimePickerFormat.Custom;

     private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
     {
         this.dateTimePicker2.CustomFormat = "dd-MM-yy";
     }

到目前为止一切顺利.但是,一旦用户选择了日期,dateTimePicker2 控件就会显示某个日期(用户选择的日期).无法再次将日期设置为空.我不想启用与 datetimepicker 控件关联的复选框.

So far so good. However, once the user selects the date, the dateTimePicker2 control shows some date ( the date the user has selected). There is no way to set the date to null again. I am not keen to enable the checkbox associated with the datetimepicker control.

我想知道是否可以将 datetimepicker 日期设置为 null.

I was wondering if it is possible to set the datetimepicker date to null.

谢谢

推荐答案

这是引用自一个旧帖子,但此站点上的其他用户已将其发布到此处

This is in reference from a post that is old but other users on this site have posted it here you go

// Use ValueChanged to decide if the value should be displayed:
    dateTimePicker1.ValueChanged += (s, e) => { dateTimePicker1.CustomFormat = (dateTimePicker1.Checked && dateTimePicker1.Value != dateTimePicker1.MinDate) ? "MM/dd/yyyy" : " "; };

    //When getting the value back out, use something like the following:
    DateTime? dt = (dateTimePicker1.Checked && dateTimePicker1.Value != dateTimePicker1.MinDate) ?  (DateTime?) dateTimePicker1.Value : null; 
    // or
    DateTime dt2 = (dateTimePicker1.Checked && dateTimePicker1.Value != dateTimePicker1.MinDate) ?  dateTimePicker1.Value : DateTime.MinValue; 

或者您可以将 CustomFormat 设置为 " " 一个空白区域,如下所示

or you can set the CustomFormat to " " an empty space like the following below

dateTimePicker1.CustomFormat= " ";

这篇关于在 C# 中的 DateTimePicker 中设置空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆