How to check whether datatable contains any matched rows?

梦想的初衷 提交于 2021-02-10 08:51:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!