Try changing your foreach
loops
foreach (var c in cre_sum_result.Entities)
{
if(c.Attributes.ContainsKey("cre_sum"))
{
TotalCre += ((Decimal)((AliasedValue)c["cre_sum"]).Value);
}
}
You need to test whether the value is there before trying to cast is. The error you are getting is a generic .Net one (more info here).
If no value is found in the field for a particular record, CRM will not include that property and so it will be missing in the collection.
You are also using =
and not +=
. This mean the total is the value of the last record, rather than a sum.
Consider the following:
var ListOfNumbers = new List<int> { 1, 2, 3 ,4 }
var total = 0;
foreach (var c in ListOfNumbers)
{
total = c;
}
Console.WriteLine(total.ToString());
would output 4
var ListOfNumbers = new List<int> { 1, 2, 3 ,4 }
var total = 0;
foreach (var c in ListOfNumbers)
{
total += c;
}
Console.WriteLine(total.ToString());
would output 10