让DateTimePicker显示空时间值 (转)

写在前面:在.net中让DateTimePicker显示一个空的时间值,也许是很容易的事情,但事实上,也不是很容易的,至少,没有 经过努力的修改和重画,你是达不到的。在修改这个控件的时候,你又常常发现会有bug。下面介绍一个方法,至少源作者是经过研究的,没有发现多少问题。

源网址
http://www.codeproject.com/KB/selection/Nullable_DateTimePicker.aspx
你可以在上述的网址找到源代码和英文的说明。

效果图
下图中,你只要按一下Delete键就可以将 DateTimePicker的值设置为空,实际的值是DateTime.MinValue,这一个简单的效果,也许是很多程序员想看到。不过学习一下这 个控件。

源代码
最重要的两个重载方法是下面俩。
protected override void OnCloseUp(EventArgs eventargs)
protected override void OnKeyDown(KeyEventArgs e)
DateTimePicker本身是支持自定义格式 的,DateTimePickerFormat.Custom,就是声明使用自定义格式的。
  public new DateTime Value
  {
   get
   {
    if (bIsNull)
     return DateTime.MinValue;
    else
     return base.Value;
   }
   set
   {
    if (value == DateTime.MinValue)
    {
     if (bIsNull == false)
     {
      oldFormat = this.Format;
      oldCustomFormat = this.CustomFormat;
      bIsNull = true;
     }

     this.Format = DateTimePickerFormat.Custom;
     this.CustomFormat = " ";
    }
    else
    {
     if (bIsNull)
     {
      this.Format = oldFormat;
      this.CustomFormat = oldCustomFormat;
      bIsNull = false;
     }
     base.Value = value;
    }
   }
  }

出处:小作坊 网ChakMan

 

C#日期控件datetimepicker保存空值方法

2009-06-01 15:37

方法一(推荐):

设置datetimepicker的属性ShowCheckBox为 true

在窗口初始化时候,添加代码this.datetimepicker1.Checked = false;

保存 日期值入库的时候,就可以根据if(this.datetimepicker1.Checked ==false),保存空值。

方 法二:

在窗口初始化函数中添加:
this.dateTimePicker1.Format=DateTimePickerFormat.Custom;
this.dateTimePicker1.CustomFormat="   ";
在日期改变事件里写:
private void dateTimePicker1_ValueChanged(object sender, System.EventArgs e)
{
this.dateTimePicker1.Format=DateTimePickerFormat.Long;
this.dateTimePicker1.CustomFormat=null;
}
这样就实现了,在程序初始化时dateTimePicker显示为空

但是,这种写法有个问题,保存入库的时候,还 要加一个判断if(this.dateTimePicker1.Text.toString()==""),保存空值;else 保存this.dateTimePicker1.value。

这种写法遇到个bug,一直没有解决,就是日期控件默认是空的,在第一次选 择一个日期后必须失去焦点才能选择新的日期,不知道什么原因?

方法三:

在日期控件上面覆盖一个文本框,然后初始化时候文 本框是空值,每次日期选择之后将值附在文本框里面。

 

http://hi.baidu.com/pollywog/blog/item/8ec254cecfd33731b600c856.html

转载于:https://www.cnblogs.com/zeroone/archive/2010/03/31/1701063.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值