如何在C#中安全地将dbnull值转换为int [英] How to safe cast dbnull value to int in C#

查看:563
本文介绍了如何在C#中安全地将dbnull值转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好

我将从datagridview到int变量的Int值进行检索。有些时候datagridview行值将为null。那时它会显示

Hello
I am retrive the Int value from datagridview to int variable. Some time datagridview row value will be null. at that time it will display

Error (Object cannot be cast from DBNull to other types.





)

Index = Convert.ToInt32(MyGrid.Rows[2].Cells[8].Value);





我尝试了什么:



我知道下面的代码我可以解决这个问题,但你可以建议我任何其他安全的方式。



What I have tried:

I know with below code i can solve this but can you suggest me any other safe way.

if(MyGrid.Rows[2].Cells[8].Value != null)
{
Index = Convert.ToInt32(MyGrid.Rows[2].Cells[8].Value);
}

推荐答案

你不能将DBNull值转换为任何类型:这就是DBNull所说的 - 这是一个特殊的表示数据库在此列中不包含值的值。

尝试将其转换为整数就像尝试使此总和一样:

You can't cast a DBNull value to any type: that's what DBNull is saying - it's a special value which says "the database contains no value in this column".
Trying to cast it to an integer is like trying to make this sum work:
x = y +

Y加什么?你不知道,我不知道,并且肯定你的数据库也不知道! :笑:



相反,试试这个:

Y plus what? You don't know, I don't know, and for sure your database doesn't know either! :laugh:

Instead, try this:

object o = MyGrid.Rows[2].Cells[8].Value;
Index = o == DBNull.Value ? 0 : (int) o;

或者用其他默认值替换零。

Or replace zero with another default value.


var index=
    (MyGrid.Rows[2].Cells[8].Value).Equals(null)
    ? 0
    : Convert.ToInt32((MyGrid.Rows[2].Cells[8].Value);

//or try This remove Value from Cell[8]

var index=
    (MyGrid.Rows[2].Cells[8]).Equals(null)
    ? 0
    : Convert.ToInt32((MyGrid.Rows[2].Cells[8].Value);


这篇关于如何在C#中安全地将dbnull值转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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