无法将空值传递给datatable列中的变量 [英] Unable to pass empty value to a variable from datatable column

查看:111
本文介绍了无法将空值传递给datatable列中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在数据表中,我有一个字符串列'运费'。在其中一个数据表行中,此列为空。我想将此列中的值传递给int变量'v_shippingcharges'。我尝试使用以下代码,但在'v_shippingcharges = ...'行收到错误我收到错误:'对象无法从DBNull转换为其他类型'。





In a datatable I have a string column 'shipping charges'. In one of the datatable row, this column is empty. I want to pass the values from this column to an int variable 'v_shippingcharges'. I tried with the following code but get error at line 'v_shippingcharges=...' I get the error as: 'Object cannot be cast from DBNull to other types'.


if (dtCurrentTable.Rows[i]["Shipping Charges"] != null)
                   {
                       v_shippingcharges = Convert.ToInt32(dtCurrentTable.Rows[i]["Shipping Charges"]);
                   }
                   else
                   {
                       v_shippingcharges = 0;
                   }

推荐答案

根据错误,该列不为空它是空的 - 它不一样......

您的问题是您尝试将NULL转换为不可为空类型的int ...

您有几个选项

1.在SQL执行ISNULL(列,0) - 或任何其他默认值

2.在代码中执行if(Convert.IsDBNull(column)){初始化一些默认值} - http://msdn.microsoft.com/en-us/library/system.convert.isdbnull.aspx [ ^ ]

3.您可以在代码中使用nullable int - http:// msdn .microsoft.com / zh-CN / library / 2cf62fcy.aspx [ ^ ]
According to the error the column isn't empty it's NULL - it's not the same...
Your problem is that you try to convert NULL to int which is not nullable type...
You have a few options
1. In SQL do ISNULL(column, 0) - or any other default value
2. In the code do if(Convert.IsDBNull(column)){initialize with some default value} - http://msdn.microsoft.com/en-us/library/system.convert.isdbnull.aspx[^]
3. You may use nullable int in your code - http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx[^]


这篇关于无法将空值传递给datatable列中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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