views:

79

answers:

2

Hi fellows, I am using Compute for summing up a datatable which has a condition. Sometimes, there are no rows inside the datatable matching my criteria so I get an exception on Compute Object cannot be cast from DBNull to other types.

Is there a way to check/filter the datatable to see if it has the desired rows, if yes only then I apply Compute. Please advice.

total = Convert.ToDecimal(CompTab.Compute("SUM(Share)", "IsRep=0"));
+2  A: 

First, assign the value to an object, which can bedone safely and tested for null values.

Second, use TryParse() if there's a chance it won't work (which is probably overkill in this scenario... The Compute function will always result in either nothing, or something that can be converted.. But I already typed the code so I'll keep it. And it's just a good habit.)

object oTotal = CompTab.Compute("Sum(share)", "IsRep=0");
Decimal total;
if(oTotal != null)
{
   if(!System.Decimal.TryParse(oTotal.ToString(), out total))
   {
        // whatever logic you need to include if the TryParse fails.
        // Should never happen in this case.
   }
}
David Stratton
Thank you David. That was very helpful.
Popo
Hey it says 'Operator '!' cannot be applied to operand of type 'object''.
Popo
What if I use total = Convert.ToDecimal(dtSum)??0; instead of tryparse ?
Popo
I fixed my if statement. Sorry. I should have seen that.
David Stratton
+2  A: 

try this

object objCompute=CompTab.Compute("SUM(Share)", "IsRep=0");
if(objCompute!=DBNull.Value)
{
total = Convert.ToDecimal(objCompute);
}
ajay_whiz