Click here to Skip to main content
15,896,348 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
report.Print(StringUtils.PadLeft(Convert.ToDateTime(now["MtgDt"]).ToShortDateString(), 33));

The above code throws an error that Object cannot be cast from DBNull to other types. I tried putting a condition of if else but that does not make sense perhaps because DATETIME is non-nullable.
Please help
Posted
Comments
Sergey Alexandrovich Kryukov 12-Jun-15 10:01am    
Other types? Which type would you want to cast DBNull then?
Do you realize that DBNull, not being exactly the same thing as C# and .NET null, still carries the same semantic, meaning "nothing", "no data"? :-)
—SA
[no name] 12-Jun-15 10:12am    
It makes perfect sense when you realize that it can be null in the database.
Afzaal Ahmad Zeeshan 14-Jun-15 15:47pm    
Why not first check whether the object is null or not.

1 solution

DATETIME is non-nullable in .NET - but it isn't in SQL, where NULL is a valid value for a DATETIME column if you configured your DB that way (and the SSMS designer defaults to "nulls allowed" for new columns).

So your database contains a row or rows where the MtgDt column has a NULL value. Either:
1) Fix your DB, replace the NULL values with "reasonable" dates, and change the column design to "NOT NULL"
Or
2) check for DBNull.Value in your code and replace it with a reasonable value (or report an error, whichever is better given your application).
C#
report.Print(StringUtils.PadLeft((now["MtgDt"] == DBNull.Value ? AReasonableDefaultValue : Convert.ToDateTime(now["MtgDt"])).ToShortDateString(), 33));
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900