如果为null

时间:2015-08-19 13:22:53

标签: c# asp.net .net datetime nullable

我有一个asp.net应用程序,我有一个文本框来输入datetime值,它保存在数据库中。

现在,当我尝试检索日期时,如果日期为空,则显示1/1/0001 12:00:00 AM。

this.FirstReceivedDate = DateTime.Parse(dr["FirstReceivedDate"].ToString());

道歉,要求改变了。现在我想在FirstReceivedDate为空时显示空白('')。

我该怎么做?

7 个答案:

答案 0 :(得分:1)

您可以尝试以下内容:

DateTime date = DateTime.Parse(dr["FirstReceivedDate"].ToString());
this.FirstReceivedDate = date != DateTime.MinValue ? date : DateTime.Now;

因为它正确解析,所以应该有效。

或者,如果您想要一个日期为null的值,您可以尝试这样的事情:

DateTime date;
if(DateTime.TryParse(dr["FirstReceivedDate"], out date))
    this.FirstReceivedDate = date != DateTime.MinValue ? date : DateTime.Now;
else
    this.FirstReceivedDate = DateTime.Now; // or whatever you want to do if "FirstReceivedDate" is not a valid date.

答案 1 :(得分:1)

DateTime变量(以及所有其他值类型)不能为null(除非您将它们显式声明为可为空),因为它们必须保存一个值。 (你现在已经说 可以为空)

您需要的修复非常简单 - 您只需检查数据行中字段的空值并正确分配null DateTime,否则使用DataRow.Field<T>分配类型安全的数据库值方法:

this.FirstReceivedDate = dr["FirstReceivedDate"] == DBNull.Value ? (DateTime?)null : dr.Field<DateTime>("FirstReceivedDate");

实际上考虑一下你应该能够做以下的事情来传播空值(未经测试):

this.FirstReceivedDate = dr.Field<DateTime?>("FirstReceivedDate");

正如你所说,如果数据库值为null,你想要一个空字符串,那么只要你显示它就可以检查DateTime的空值:

textBox1.Text = this.FirstReceivedDate == null ? "" : this.FirstReceivedDate.ToString();

答案 2 :(得分:0)

this.FirstReceivedDate = DateTime.Parse(dr["FirstReceivedDate"].ToString());

if (this.FirstReceivedDate == DateTime.MinValue)
    this.FirstReceivedDate = DateTime.Now;

测试FirstReceivedDate是否等于DateTime的最小值(您在问题中指定)。如果是这样,只需将其设置为当前日期/时间。

答案 3 :(得分:0)

DateTime date = DateTime.Parse(dr["FirstReceivedDate"].ToString());     
this.FirstReceivedDate = date = =default(DateTime) ? DateTime.Now : date;

这里真正的问题是为什么你收到1/1/0001 12:00:00 AM当你说日期时间可以为空?,你应该收到DBNull,检查你的数据库,该字段应该接受空值。

答案 4 :(得分:0)

我已创建此扩展方法以尝试转换为datetime,如果函数返回null,则该值不是有效的日期时间

     public static DateTime? ToDateTimeCheck2(this string valor)
{
       var isDate = true;

        DateTime dt;
        isDate  = DateTime.TryParse(valor, out dt);

        if (isDate)
            return dt;
        else
        return null;


}

然后在你的代码中你可以说

this.FirstReceivedDate =( dr["FirstReceivedDate"].ToDatetimeCheck2() == null)? "" : dr["FirstReceivedDate"].ToDatetimeCheck2();

没有扩展方法的其他选项:

 string t = "123";

            DateTime result;

            string testing = (DateTime.TryParse(t,out result ))? result.ToShortDateString() : string.Empty;

答案 5 :(得分:-1)

试试这个:

DataRow dbField = dr["FirstReceivedDate"];

this.FirstReceivedDate = dbField == null 
    ? String.Empty 
    : dbField.ToString() ;

答案 6 :(得分:-1)

以下代码有效。

string date = dr["FirstReceivedDate"].ToString();
this.FirstReceivedDate = date == "" ? (DateTime?)null : DateTime.Parse(date);

感谢大家的帮助。

相关问题