Dynamics CRM 2011: Rolling up subgrid totals to a form field

MSCRM does require a little bit of coding when we try to add form field values. A common scenario is the addition of two inputted field values to make a third calculated value. This is easily achieved by using the method “Xrm.Page.getAttribute(‘ATTRIBUTE NAME’).

For example the following method, when invoked in a form’s OnSave event will add two floating point fields “new_firstvalue” and “new_secondvalue” and set the value of the field “new_calculatedthirdvalue”:


function calculateThirdValue ()


   var FirstValue = Xrm.Page.data.entity.attributes.get(“new_firstvalue”).getValue();

   var SecondValue = Xrm.Page.data.entity.attributes.get(“new_secondvalue”).getValue();

   varCalculatedThirdValue = parseFloat(FirstValue )+parseFloat(SecondValue);



Lately I needed to do something a little different. I wanted to roll up values from a subgrid view embedded in my form. So after a little experimentation, I came up with this method which can be re-used for different subgrid columns. So in my OnLoad even I invoke a method like this:

function calculateRolledUpTotals()


  //Calculate total of column 1

   var col1Total = aggregateGridFields(‘new_column1’);

   Xrm.Page.getAttribute(‘new_column1total’).setValue(parseInt(col1Total ));

   Xrm.Page.getAttribute(‘new_column1total’).setSubmitMode(‘always’); …


and this re-usueable method then totals the subgrid values for the column pass to is by name: 

function aggregateGridFields (columnName)


   var gridControl = document.getElementById(‘queryset’).control;

   var ids= gridControl.get_allRecordIds();

   var aggCount=0;

   for(i = 0; i < ids.length; i++)


var cellValue = gridControl.getCellValue(columnName,ids[i]);

      if (parseInt(cellValue))    


      aggCount+=parseInt(cellValue, 10);



return aggCount;


Comments (3)

  1. Justin says:

    Only problem is this only calculates what's currently showing in the grid. How do we calculate ALL items, not just those on the current page?

  2. Shaun says:

    Hi, what does 'queryset' refer too?

    Is it the name of the entity your working on, or the name of the entity is sub grid refers too?

  3. DermotB says:

    Hi Shaun, queryset is a bit like a returned dataset in ADO, so it's the set of records in the subgrid – and then the loop totals the relevant value.

    @Justin – sorry I didn't reply back when you made that comment – but off the top of my head I think you'll need a database query to pull all the records.