且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将日历控件值设置为null

更新时间:2023-01-31 21:10:04

我认为控件 System.Web.UI.WebControls.Calendar 在这方面是有缺陷的。 MSDN文档说默认值是 DateTime.MinValue 。真是太遗憾了。这意味着此控件中使用的此值(否则有效)大致相当于无值或未设置状态。这是错的。请参阅:

https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.calendar.selecteddate%28v=vs.110%29.aspx [ ^ ]。



请注意, System.DateTime 类型不能为null,因为它是值类型,而不是引用类型。您可以使用 nullable 类型 System.DateTime?。太糟糕了,这不是这种控制的工作方式。



任何实际的解决方法?好吧,你可以继承这个控件,创建一个派生类NullableCalendar。添加 System.DateTime?的其他属性。在内部,处理事件 SelectionChanged

https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.calendar.selectionchanged% 28v = vs.110%29.aspx [ ^ ]。



在处理程序中,当某些真实 选择日期,将您的可空属性分配给 SelectedDate 。这样,通过从真正选择中检查此属性为null,您将能够告诉控件的从未选择状态。考虑一些自定义渲染(例如背景颜色),它可以直观地指示这种从未选择状态。



-SA

i'm using a Calendar control in a formview, and having problems only when no date is selected,in sql one default date is comming.this field is not a mandortary field,when we select date then only value want to come otherwise we want null vale. How can i fix this issue.

I think the control System.Web.UI.WebControls.Calendar is defective in this respect. MSDN documentation says that the default value is DateTime.MinValue. This is a shame, really. It means this value, otherwise valid, is used in this control is roughly equivalent to "no-value" or "unset" status. This is wrong. Please see:
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.calendar.selecteddate%28v=vs.110%29.aspx[^].

Note that you cannot have null for System.DateTime type, because it is a value type, not a reference type. You could use the nullable type System.DateTime? instead. Too bad, this is not how this control works.

Any practical work-around? Well, you can subclass this control, create a derived class "NullableCalendar". Add additional property of the System.DateTime?. Internally, handle the event SelectionChanged:
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.calendar.selectionchanged%28v=vs.110%29.aspx[^].

In the handler, when some "real" date is selected, assign your nullable property to SelectedDate. This way, you will be able to tell "never selected" status of the control by checking this property for null from the "really selected". Think about some custom rendering (such as background color) which would indicate this "never selected" status visually.

—SA