如果date字段为空,则返回null [英] if date field is empty return null
本文介绍了如果date字段为空,则返回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.net [ ^ ],
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 theDateTimePicker
controls. For ASP.NET, it could be those found in my past answers:
TextBox allow only (HH:mm tt) format using asp.net[^],
DateTimePicker Web Control[^].
Good luck,
—SA
这篇关于如果date字段为空,则返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文