如果date字段为空,则返回null

编程入门 行业动态 更新时间:2024-10-28 06:28:15
本文介绍了如果date字段为空,则返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 如果文本框为空,我试图返回null,否则返回日期,但它无法将datetime转换为null。

public DateTime Date { get { if (calendarTextBox.Text == String .Empty) { return null ; } else { return 转换。 ToDateTime(calendarTextBox.Text); } } set { calendarTextBox.Text = 值 .ToShortDateString(); } }

提前感谢!

解决方案

DateTime不能为null 。除了使它成为一个字符串,我知道两个选项。 第一个选项,使用MinValue(或MaxValue)日期作为哨兵值。然后在需要的地方检查MinValue。

return DateTime.MinValue; // 设置为MinValue ... // 稍后代码检查MinValue if ( Date!= DateTime.MinValue) { // 做点什么 }

选项二,将DateTime声明为可空。这不再是DateTime对象,当您将可空的DateTime映射到正常的DateTime时,您需要进行类型转换。

// ?将此声明为可以为空的DateTime,例如DateTime? public DateTime? Date2 { get { if ( calendarTextBox.Text == String .Empty) { return 空; } else { return 转换。 ToDateTime(calendarTextBox.Text); } } set { // 然后你必须转换DateTime?键入日期时间类型 calendarTextBox.Text = Convert.ToDateTime( value )。ToShortDateString(); } }

解决方案1已经足够好了,我建议第二个选项。但是,使用文本框时间不是一个好主意。使用 DateTimePicker 控件之一要好得多。对于ASP.NET,它可能是我过去的答案中找到的那些: TextBox仅允许(HH:mm tt)格式使用asp [ ^ ], DateTimePicker Web Control [ ^ ]。 祝你好运,
-SA

im trying to return null if the textbox is empty, otherwise return the date, but it cant convert a datetime to null.

public DateTime Date{ get { if (calendarTextBox.Text == String.Empty) { return null; } else { return Convert.ToDateTime(calendarTextBox.Text); } } set { calendarTextBox.Text = value.ToShortDateString(); } }

thanks in advance!

解决方案

DateTime cannot be null. Other than making it a string I know of two options. First option, use the MinValue (or MaxValue) date as sentinel value. Then have checks for the MinValue where needed.

return DateTime.MinValue; // set to MinValue ... // later in code check for MinValue if (Date != DateTime.MinValue) { // do something }

Option two, declare the DateTime as nullable. This will not be a DateTime object any longer and you will need to do type conversion when you map the nullable DateTime to a normal DateTime.

// the ? declares this as a nullable DateTime, e.g. DateTime? public DateTime? Date2 { get { if (calendarTextBox.Text == String.Empty) { return null; } else { return Convert.ToDateTime(calendarTextBox.Text); } } set { // you must then convert the DateTime? type to a DateTime type calendarTextBox.Text = Convert.ToDateTime(value).ToShortDateString(); } }

Solution 1 is good enough, I would recommend the second option. However, using a text box for time is not a good idea. It's much better to use one of the DateTimePicker controls. For ASP.NET, it could be those found in my past answers: TextBox allow only (HH:mm tt) format using asp[^], DateTimePicker Web Control[^]. Good luck,
—SA

更多推荐

如果date字段为空,则返回null

本文发布于:2023-10-20 01:21:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1509409.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   为空   date   null

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!