对象不能从dbnull转换为datetime的其他类型 [英] object cannot be cast from dbnull to other types for datetime

查看:439
本文介绍了对象不能从dbnull转换为datetime的其他类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

report.Print(StringUtils.PadLeft(Convert.ToDateTime(now [MtgDt])。ToShortDateString(),33));



上面的代码抛出一个错误,即无法将对象从DBNull强制转换为其他类型。我尝试设置if if的条件,但这可能没有意义,因为DATETIME是不可为空的。

请帮助

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

推荐答案

DATETIME在.NET中不可为空 - 但它不在SQL中,如果您以这种方式配置数据库,则NULL是DATETIME列的有效值(并且SSMS设计器默认为新列的允许空值)。 br />


因此,您的数据库包含一行或多行,其中MtgDt列具有NULL值。要么:

1)修复数据库,用合理日期替换NULL值,并将列设计更改为NOT NULL



2)检查代码中的DBNull.Value并将其替换为合理的值(或报告错误,无论哪个更适合您的应用程序)。

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).
report.Print(StringUtils.PadLeft((now["MtgDt"] == DBNull.Value ? AReasonableDefaultValue : Convert.ToDateTime(now["MtgDt"])).ToShortDateString(), 33));


这篇关于对象不能从dbnull转换为datetime的其他类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆