C#:对象不能从 DbNull 转换为其他类型 [英] C#: Object cannot be cast from DbNull to other types

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

问题描述

我在网上阅读了几篇关于此的帖子,但没有一篇能解决我的问题.网上发布的大多数问题都指向我检查数据库中的 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.

昏暗

推荐答案

检查 DbNull before 调用 Convert.ToInt32:如您所见,如果值为 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屋!

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