Click here to Skip to main content
15,921,622 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.
Posted
Updated 7-Aug-17 5:30am
v4
Comments
ZurdoDev 7-Aug-17 11:31am    
Your value is coming out null. But you have a much bigger problem. You keep opening and closing the connection inside a loop which is a very bad way of handling resources.

Write a sql query that does something like this
SELECT SUM(itemqty) AS TotalSum
FROM someTable
WHERE ids BETWEEN 1 AND 100

and then there is no loop.
G3Coder 7-Aug-17 11:32am    
Hi,

Without going into too much detail on what you have posted - try a group by clause in your SQL.

G

1 solution

Your query returns no values.
Use the debugger to confirm the value of i, 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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900