Nullable Object must be # 2

I am trying to reuse the same code that I always used, but now it is facing an error.

I look at various user tables, and there I do this:

DateTime dcdt = (DateTime)u.DateCreated;
DateTime lldt = (DateTime)u.LastLogon;
userRow["DateCreated"] = dcdt.ToShortDateString();

inside the loop. I get an error message:

System.InvalidOperationException: Nullable object must have a value.

The error highlights the line "lldt" , not the "dcdt", which comes first. This is strange in itself. Both of these fields in the allow nulls database are checked. And both of them can be zero or nothing can be zero.

The two values ​​are both listed as DateTime? types through intellisense.

I do not understand why ASP.NET refuses to allow me to print a null value for null dates. If it is empty / null, the logic assumes that ASP.NET should simply not print anything.

? , , null DateTimes, , .

+5
5

, u.LastLogon DateTime?. , . DateTime, , . .

, , HasValue:

userRow["LastLogon"] = u.LastLogin.HasValue ? 
                       (object) u.LastLogin.ToShortDateString() : DBNull.Value;

LastLogon DateTime, :

userRow["LastLogon"] = u.LastLogin.HasValue ? 
                       (object) u.LastLogin.Value : DBNull.Value;
+12

.NET.NET null SQL NULL. SQL Null System.DBNull. , [ null] .NET.

+1

, (dcdt.ToShortDateString()) DateTime? (, , null). :

dcdt.HasValue ? dcdt.ToShortDateString() : String.Empty;

EDIT ( ): DateTime. .

№ 2 ( ):

:

if (dcdt.HasValue) 
{ userRow["DateCreated"] = dcdt.ToShortDateString(); } 
else
{ userRow = DbNull.Value }
+1

- :

DataTable  dt       = ExecuteSomeQuery() ;
object     value    = dt.Rows[0]["nullable_datetime_column"] ;
DateTime?  instance = value != null && value is DateTime ? (DateTime?)value : (DateTime?)null ) ;

NULL, System.DBNull, DateTime ( -— int, string ..). , , , .

+1

I saw that Dexter asked how he should do it. Well, I would create an extension.

static class DateTimeExtensions
{
    public static string ToString(this DateTime? dateTime, string format)
    {
        return dateTime.HasValue ? dateTime.Value.ToString(format) : String.Empty;
    }
}

And then you can do:

DateTime? dt = null;
DateTime? dt2 = DateTime.Now;
Console.WriteLine(dt.ToString("dd-MM-yy"));
Console.WriteLine(dt2.ToString("dd-MM-yy"));

Note that I can call the extension method of type NULL if the object is null.

+1
source

All Articles