Click here to Skip to main content
15,907,905 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,


int sum = Convert.ToInt32(dt.Compute("SUM(Amount)", "Section>0"));

I want to use aggregate function sum() to get total amount from datatable for specific conditions,but the above statement throws error object cannot be cast from dbnull to other types
Posted
Comments
[no name] 15-Oct-15 5:20am    
It seems Amount column value is NULL for some records in your DataTable dt object. You can overcome the exception putting 0 instead of NULL.

If it doesn't resolve your problem, please provide code how data is coming to your DataTable.
7045Jeegnesh 15-Oct-15 5:46am    
Yes Manas_Kumar Is right:

dt.defaultview.rowfilter="Amount is Not Null"

int sum = Convert.ToInt32(dt.defaultview.Totable.Compute("SUM(Amount)", "Section>0"));

try This
Parag Sudhir Chaudhari 16-Oct-15 1:37am    
Thanks its working now
W Balboos, GHB 15-Oct-15 6:48am    
More Options:

You can handle this on the SQL side using ISNULL(...,...) so that you never return a null from the query.

You can test the value in a prior statement for (dbnull) and then handle it as you see fit.

1 solution

Try this:
C#
int sum = 0;
object calc = dt.Compute("SUM(ISNULL(Amount, 0))", "Section>0");
bool converted = Integer.TryParse(calc, sum);
if (!converted) // some message;
else
//work normally
 
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