CRM 2011 – Javascript and Subgrids code example

Someone posted a comment on my blog asking about Javascript and subgrids.  Although I don’t yet need to do anything with Javascript and subgrids I thought I would.  It certainly shows the benefit of Microsoft having forums for CRM problems.

Firstly the question is how to get the values from a subgrid, I found this good forum post and the Javascript is below

You can inspect the subgrid values on save by doing the following:

var gridControl = document.getElementById('subgrid_id').control; 
var ids = gridControl.get_allRecordIds(); 
 for(i = 0; i < ids.length; i++) 

 var cellValue = gridControl.getCellValue('column_name', ids[i]); 
 // logic 

Doing this on load is a bit more challenging since subgrids are loaded asynchronously and aren’t likely to be done loading when the form onload event fires. You can check the grid periodically though to see when it’s done loading by calling a function like the following in your form onload:

function subGridOnload() 

var grid = document.getElementById('grid_identifications'); 
 if (grid.readyState!="complete") 

 // delay one second and try again. 
 setTimeout(subGridOnload, 1000); 

// logic 

I then also found a forum post on attaching events to a subgrid, which you can read here

For CRM 2011, your code should look like this:

if (Xrm.Page.ui.getFormType() != 1) {

  Xrm.Page.ui.controls.get("IFRAME_OpportunityLines").onreadystatechange = function oppLineTotals() {
    if (Xrm.Page.ui.controls.get("IFRAME_OpportunityLines").readyState == 'complete') {
      var iFrame = frames[];
      iFrame.document.all.crmGrid.attachEvent("onrefresh", GridRefresh);

Funny thing, the sdk recomended function did not work for me (i.e. Xrm.Page.ui.controls.get(“GridName”) ), and yet the following works (tested!)

var grid = document.getElementById("GridName");
grid.attachEvent("onrefresh", EventHandlerFunction);

because the (Html Component) actually includes a public event “onrefresh”… And this event can be handled with any function. We dont need to dive into the eventManager and scriptEvents.

41 thoughts on “CRM 2011 – Javascript and Subgrids code example

  1. Dan Rigby May 26, 2011 / 2:04 pm

    “Funny thing, the sdk recomended function did not work for me (i.e. Xrm.Page.ui.controls.get(“GridName”) ), and yet the following works (tested!)”

    From what I’ve read, this was a bug introduced in Rollup 1 of CRM 2011.


  2. Dan Rigby May 26, 2011 / 2:12 pm

    Also, in my testing, the subgrid onrefresh event doesn’t get fired when the grid first loads it’s data, only on subsequent clicks of the refresh button.


  3. Bhanu Bharadwaj June 1, 2011 / 10:14 am

    HI Every one,
    I am creating a simple form in crm2011 for calculating salary. I have added the field on the form which are following
    H.R.A. = 10 percent of basic;
    T.A. = 20 percent of basic;
    Gross = Basic + H.R.A.+T.A.;
    The requirement is this , When I will enter the value in basic it should auto calculate the value of other field.
    Kindly tell me how can i do this and where i write the code.


  4. Bhanu Bharadwaj June 2, 2011 / 5:37 am

    How Can register crm2011 Plug-in.


  5. jz June 8, 2011 / 6:40 pm

    i need to access the total record count dispalyed at bottom of the grid inside an iframe. please reply back if you have answer


  6. Houseedition June 22, 2011 / 12:50 am

    Hi jz, I dont understand what total record is that you need, but I found this two methods.
    – gridControl.get_selectedRecordCount()
    – gridControl.get_totalRecordCount()

    I have a question, How can I set value for some cell, I need add a link

    var gridControl = document.getElementById(‘subgrid_id’).control;
    var ids = gridControl.get_allRecordIds();
    for(i = 0; i < ids.length; i++)
    var cellValue = gridControl.getCellValue('column_name', ids[i]);
    if (cellValue=="")

    I hope that can help me, Thanks!


  7. Ian August 16, 2011 / 4:03 pm

    is it possible to change the ‘view’ that the subgrid uses via javascript.
    i’ve used the ‘addCustomView’ for a lookup control and would like the same concept for the subgrid


  8. Gareth Tucker August 22, 2011 / 6:57 am

    Hi, any idea whether you can change the query behind a sub-grid via java script – i.e. modifiy the fetch xml to filter the results returned.


  9. pt72 August 31, 2011 / 3:19 pm

    I believe this will only get you records in the current page of the subgrid view. If that is correct, any idea how to retrieve all rows from all pages? My only thought is to use an oData call. Thanks.


  10. Ciaran November 8, 2011 / 10:49 pm

    A problem has arisen recently with our CRM online where var gridControl = document.getElementById(‘subgrid_id’) is now returning null. I’ve looked at the HTML of the from in the browser and my grid “name” is there as an id. Anyone have any clue as to why the call to get the subgrid element fails and if there’s any workaround? The crm 2011 client side sdk says calls to document.getElementById(…) are not supported. I assume the reason is that MS don’t want to guarantee the HTML they output won’t change but if my subgrid is there an an element with an id = “my subgrid name”, how come the JS call returns null? Perplexed…


  11. Jonathan November 24, 2011 / 7:56 am

    “I believe this will only get you records in the current page of the subgrid view. If that is correct, any idea how to retrieve all rows from all pages? My only thought is to use an oData call. Thanks.”

    var ids = gridControl.get_allRecordIds();

    I have noticed this too, does anyone know how to retrieve the IDs for all rows from all pages?


  12. damien November 29, 2011 / 11:00 am

    for me it said that “get_allRecordIds” don’t exist on the control.


  13. Lucas November 29, 2011 / 8:55 pm

    The following will return the number of records found in the sub grid for line items on the opportunity form.

    function TimeOutGrid() {
    setTimeout(WriteInCount, 10000);
    function WriteInCount() {
    var spanList = document.getElementById(‘opportunityproductsGrid_d’).getElementsByTagName(“span”);
    for (var i = 0; i < spanList.length; i++) {
    if (spanList[i].id != null && spanList[i].id == "opportunityproductsGrid_ItemsTotal")


  14. damien November 30, 2011 / 8:44 am

    thanks it works now. how can i retrieve de GUID of the row because i can’t display it the column in the sub grid then: how can i retrive it ? thanks


  15. damien December 2, 2011 / 8:32 am


    im looking a way to retrieve only selected record/ row. for the moment it retrieve all row/record.


  16. Lucas December 5, 2011 / 8:43 pm

    You can use JSCRIPT to get your id.

    getSelectedRows : function(id){

    var rows = [];

    var gridBodyTable = $(‘#’+id).contents().find(‘#gridBodyTable’);
    var oid = $(o).attr(‘oid’);
    var selected = $(o).attr(‘selected’);
    //console.log(‘oid:’,oid,’ — ‘,’selected:’,selected)
    //console.log(typeof (selected));

    if(selected == true){
    rows[rows.length] = oid;
    return rows;


  17. Vineet December 26, 2011 / 5:02 pm


    I am setting up the url of iframe in Contract entity using JS. My iframe url points to Associated View url. Now, I want to get the id of a record which has been selected in an iframe using JS.

    Fyi, I have tried the below code.

    var gridControl = document.getElementById(“yourSubGridName”).control;
    var ids = gridControl.get_selectedIds();

    I cannot see the method name as get_selectedIds() which will give you the id of a selected row. Please suggest..



  18. NewPath Technologies (@newpathtech) February 14, 2012 / 9:23 pm

    I am not sure the recursive call to keep waiting for the grid container will work. I tried this technique and got the code to keep calling itself. Here’s the approach I tried which is similar to your approach but rather uses setTimeout to call another function that reads the data from the grid after a predetermined amount of time. I found 1000-2000 ms seems to work well. But I realize it is not ideal.


  19. Subhagya April 23, 2012 / 10:04 pm

    Hello Everyone……

    I want to divide one field on the CRM form by another field and get the result on the third field.

    Kindly suggest


  20. Subhagya April 23, 2012 / 10:06 pm

    like…… if I have got:

    1) Projects Opened
    2) Projects Awarded

    3) Average of Awardation => It should automatically calculate => Projects Awarded/Project Opened*100

    Kindly suggest.


    • Hosk April 23, 2012 / 10:35 pm

      have a plugin which runs on the update event and then do the calculation


  21. himanshu May 26, 2012 / 5:31 am

    How can I use this when form type is 1???


  22. Darren June 19, 2012 / 2:41 pm

    Hello, I have used your code to attach an event to the the subgrid on refresh and it worked fine. Now I upgraded to UR8 and it stopped working, Any idea why and how i can fix it please?


  23. Sharjeel September 26, 2013 / 4:36 am

    Here’s my situation:

    I have an entity, Project Work. The form has the field “Time Allocated (hrs)”. I have Project Work as a subgrid in the Project form. The Project form has “Total Allocated (hrs)”. This is because one Project can have many “Project Work”. How can I show the sum of all the “Time Allocated (hrs)” from Project Work in the “Total Allocated (hrs)” on the Project form?

    Hope this had made sense.
    Thank you


    • Hosk September 26, 2013 / 8:29 am

      I think you would probably need a plugin calculating the Total Allocated hours, this would probably be triggered by updating/saving of a project work entity.

      then you just show that field on the form.


  24. Chandan Bharti May 16, 2014 / 11:02 am

    Hi, I wan’t to update parent record’s id via a button placed on sub grid. Can some body please help me in this.


  25. Shaun Harrison June 30, 2014 / 3:43 pm

    Hi, I used your 2013 code to try make it work for my grid, but I keep getting Null returned
    I believe it might be to do with the ids as its getting the record id’s in one long string

    Any idea how to resolve this problem?



  26. Dh kumar November 27, 2015 / 12:08 pm

    Hi All,

    I am stuck at this lone of code which is not getting recognised. Can some one plz help!
    var gridControl = document.getElementById(“yourSubGridName”).control;
    var ids = gridControl.get_selectedIds();

    I cannot see the method name as get_selectedIds() which will give you the id of a selected row. Please suggest..



    • Hosk November 27, 2015 / 12:27 pm

      Are you using CRM 2011?


      • Dh kumar November 27, 2015 / 1:58 pm

        Hi hosk.

        Thanks for reply.
        No , I am using Dynamic CRM 2015 onpremise to launch modal window by capturing Quick view subgrid row on double click. Plz point me in right direction as i struggled much with this.

        I have scenario for which i need solution as i referred many blog posts but didn’t help.

        On phone call entity form i have placed/ inserted a subgrid of quickview for customEntity1. As i can see the records in subgrid and once i click on 1st column which is hyperlinked get’s open with all the pre populated values in entity form. but i don’t want in this way because i need to enter again phone detail as it’s already navigated and lost record data instead i want to open the subgrid row highlighted/ selected record in modal window so that i can come back on phone call form without losing data. I am using Dyn CRM 2015 onpremise.

        Please help for this!




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.