C#中出现错误 [英] Error is coming in C#
本文介绍了C#中出现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图总结一些项目的数量,所以我写了一个for循环。
因为我在sql quey和executioncalar()的帮助下获取了itemid和item的最大值这两个值存储在numlow和numhigh变量中。
我在I中存储了numlow值,而我在for循环中使用了i。
当我运行时
代码一切正常如下
< pre> for(int i = lownum; i< = highnum; ++ i)
{
con.Close();
con.Open();
SqlCommand qty = new SqlCommand(从invDB中选择itmqty,其中itemid ='+ i + '',con);
double quant = Convert.ToDouble(qty.ExecuteScalar());
当我将sum()添加到itmqty时总和(itmqty)它显示错误
。其中数量也为零。
错误是
对象无法从DBNull转换为其他类型
我尝试过:
我用google搜索但没有合适的结果。
解决方案
你的查询没有返回值。
使用调试器确认<$的值c $ c>我,并手动检查您的数据库以确保数据符合您的预期。
如果您的查询不返回任何值,ExecuteScalar返回DbNull - 你不能将它转换为double。
如果它应该没有匹配的值,那么你需要在尝试转换返回值之前检查null值。
I am trying to sum the quantity of some items so I wrote one for loop.
for that I took max of itemid and min of itemid with the help of sql quey and executescalar() and that two values stored in numlow and numhigh variables.
I stored numlow value in "I" and that "i" i am using in for loop.
when I am running the code everything is ok like below
<pre> for (int i = lownum; i<= highnum; ++i) { con.Close(); con.Open();
SqlCommand qty = new SqlCommand("select itmqty from invDB where itemid='"+i+"'", con); double quant = Convert.ToDouble(qty.ExecuteScalar());
when I added sum() to that itmqty like sum(itmqty) it is showing error
.Some where quantity is zero also.
Error is "
Object cannot be cast from DBNull to other types"
What I have tried:
I googled but came with no suitable results.
解决方案
Your query returns no values.
Use the debugger to confirm the value ofi
, and manually check your DB to ensure that the data is what you expect it to be.
If your query returns no values, ExecuteScalar returns DbNull - and you can't convert that to a double.
If it's supposed to work with no matching values, then you need to check for null before attempting to cast the return value.
这篇关于C#中出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文