问题
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"));
回答1:
try this
object objCompute=CompTab.Compute("SUM(Share)", "IsRep=0");
if(objCompute!=DBNull.Value)
{
total = Convert.ToDecimal(objCompute);
}
回答2:
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.
}
}
来源:https://stackoverflow.com/questions/3455586/how-to-check-whether-datatable-contains-any-matched-rows