C#:无法将对象从DbNull强制转换为其他类型 [英] C#: Object cannot be cast from DbNull to other types
问题描述
我已经在线阅读了几篇文章,但是都没有解决我的问题.在线发布的大多数问题都指向我要检查数据库中的Dbnull值,而我正在代码中进行此操作.
I have read several posts on this online, but none of them have resolved my issue. Most of the questions posted online point me towards checking Dbnull values from the database and I am doing that in the code.
以下是引发异常的代码:
Here's the code where the exception is thrown:
int rowNum = Convert.ToInt32(dataTable.Rows[r][dataTable.Columns.Count - 2]);
这是我检查dbnull值的代码:
Here's the code where I am checking for the dbnull values:
for (int r = 0; r < dataTable.Rows.Count - 1; r++) //rows
{
for (int c = 1; c < dataTable.Columns.Count - 2; c++)
{
object val = dataTable.Rows[r][c];
if (!val.Equals(DBNull.Value))
{
haveValues = true;
}
}
}
在这里,我正在从excel电子表格中读取值.
Here I am reading the values from the excel spreadsheet.
请指出正确的方向.预先感谢.
Please point me in the right direction. Thanks in advance.
Dimpy
推荐答案
在调用Convert.ToInt32之前检查DbNull:如您所见,如果值为DbNull,则会引发异常.像这样:
check for DbNull before calling Convert.ToInt32: as you have seen, this will raise an exception if the value is DbNull. something like:
object x = *value from db*
int y;
if (x != DbNull.Value)
y= Convert.ToInt32(x);
else
//handle null somehow
这篇关于C#:无法将对象从DbNull强制转换为其他类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!