title: How do I get a column to be sort in descending order upon loading?
body: <p>I'm wondering how do I get a sorted column in descending order upon loading.  I have seen some questions/answers in stack-overflow but it all depends on the jqGrid configuration.  That I haven't got it to work...  It need to be done locally once the data is received from the server.</p>
  
  <p>Thanks..</p>
  
  <pre class="lang-html prettyprint-override"><code>&lt;link rel="stylesheet" type="text/css" href="../css/jquery-ui-v1.10.3.themes/base/minified/jquery-ui.min.css" /&gt;
  &lt;link rel="stylesheet" type="text/css" href="../css/jqgrid-v4.5.0/ui.multiselect.css" /&gt; 
  &lt;link rel="stylesheet" type="text/css" href="../css/jqgrid-v4.5.0/ui.jqgrid.css" /&gt;  
  &lt;link rel="stylesheet" type="text/css" href="../css/jqgrid-v4.5.0/ui.jqgrid-bio-override.css" /&gt;
  &lt;script src="../scripts/jquery-ui-v1.10.3/minified/jquery-ui.min.js" type="text/javascript"&gt;&lt;/script&gt;
  &lt;script src="../scripts/jqgrid-v4.5.0/ui.multiselect.js" type="text/javascript"&gt;&lt;/script&gt;
  &lt;script src="../scripts/jqgrid-v4.5.0/i18n/grid.locale-en.js" type="text/javascript"&gt;&lt;/script&gt;
  &lt;!--&lt;script src="../scripts/jqgrid-v4.5.0/jquery.jqGrid.min.js" type="text/javascript"&gt;&lt;/script&gt;--&gt;
  &lt;script src="../scripts/jqgrid-v4.5.0/jquery.jqGrid.src.js" type="text/javascript"&gt;&lt;/script&gt;
  &lt;script type="text/javascript"&gt;
      $(document).ready(function () {
          &lt;% var httpPrefix = (EnvironmentSetting.WebServerEnvironment_DeveloperMachine == true ? "http" : "https"); %&gt;
          &lt;% var urlRandom = new System.Random(5); %&gt;
          &lt;% var httpAdditionalDetailToken = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + urlRandom.Next(1000).ToString(); %&gt;
          &lt;% var postQuickQuoteSalePrice = (String.IsNullOrEmpty(Request["QuickQuoteSalePrice"]) == true ? "" : Convert.ToString(Request["QuickQuoteSalePrice"])); %&gt;
  
          //My Inventory Spreadsheet...
          var jqgridSpreadsheetId = 'MyInventoryJqgrid_Spreadsheet';
          var jqgridPagerId = 'MyInventoryJqgrid_Pager';
          var jqgridGroupColumnHeader = 'MyInventoryJqgrid_GroupColumnHeader';
          var jqgridDialogLinkOptions = 'MyInventoryJqgrid_PopupDialogLinkOptions';
          var jqgridColumnIdStockNumber = 1;
          var jqgridColumnIdVin = 2;
          var jqgridColumnIdInventoryTrackerLocationId = 13;
          var jqgridColumnNameLinks = "Links";
          var jqgridHiddenDialog1 = "";
          //My Inventory Summary Spreadsheet...
          var jqgridSummarySpreadsheetId = 'MyInventorySummaryJqgrid_Spreadsheet';
  
          //var jqgridData = '{"total":3,"page":1,"records":3,"rows":[{"id":1,"cell":["73157978","1234","1GTCS149698119451","2009","GMC","Canyon Regular Cab","SLE Pickup 2D 6 ft","34555","4500.00","2013-04-30","0.00","4500.00","14",""]},{"id":2,"cell":["72174115","","1G1JE6SH0C4134329","2012","Chevrolet","Sonic","LTZ Hatchback Sedan 4D","0","100.00","2013-01-14","0.00","100.00","120",""]},{"id":3,"cell":["72167761","Rrrrr","1GNEK13TX1R173136","2001","Chevrolet","Tahoe","Sport Utility 4D","5000","6000.00","2013-01-11","0.00","6000.00","123","San Francisco"]}]}';
  
          //=====================================================================================================================================================================================================
          //=====================================================================================================================================================================================================
          //My Inventory Spreadsheet...
          //=====================================================================================================================================================================================================
          //=====================================================================================================================================================================================================
          //jqGrid Plugin...
          //http://www.trirand.com...
          //http://www.codeproject.com/Articles/201883/jqGrid-Quick-Tips...  //Useful quick-tip to get up and going fast...
          $('#'+jqgridSpreadsheetId).jqGrid({
              url: '../websrvc/JqGrid.ashx',
              datatype: 'json',
              mtype: 'POST',
              postData: { WhichJqgridTemplate: '&lt;%=JqqridTools.Template.MyInventory%&gt;', WhichAction: '&lt;%=JqqridTools.Action.Display%&gt;', WebpageQuickQuoteSalePrice: '&lt;%=postQuickQuoteSalePrice%&gt;' },
              colNames: ['Id', 'Stock Number', 'VIN', 'Year', 'Make', 'Model', 'Trim', 'Mileage', 'Purchase Price', 'Stock Date', 'Repair Cost', 'Total Cost', 'Days In Inventory', 'Hidden-Inventory-Tracker-Location-Id', 'Inventory Tracker Location', 'Links'],  //Display Text in Column Header...
              colModel: [
                         { name: 'Id', index: 'Id', sorttype: 'int', width: 0, align: 'left', hidden: true, hidedlg: true },  //"hidedlg" is use to hide the hidden column in "Column Chooser"...
                         { name: 'StockNumber', index: 'StockNumber', sorttype: 'text', width: 100, align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
                         { name: 'Vin', index: 'Vin', sorttype: 'text', width: 140, align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
                         { name: 'Year', index: 'Year', sorttype: 'int', width: 50, align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
                         { name: 'Make', index: 'Make', sorttype: 'text', width: 80, align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
                         { name: 'Model', index: 'Model', sorttype: 'text', width: 80, align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
                         { name: 'Trim', index: 'Trim', sorttype: 'text', width: 100, align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
                         { name: 'Mileage', index: 'Mileage', sorttype: 'int', width: 60, align: 'center', formatter: 'number', formatoptions: {decimalSeparator:'',thousandsSeparator:',',decimalPlaces:0,defaultValue:'0'} },
                         { name: 'PurchasePrice', index: 'PurchasePrice', sorttype: 'currency', width: 80, align: 'center', formatter: 'currency', formatoptions: {decimalSeparator:'.',thousandsSeparator:',',decimalPlaces:2,defaultValue:'0.00',prefix:'$',suffix:''} },
                         { name: 'StockDate', index: 'StockDate', sorttype: 'date', width: 80, align: 'center', formatter: 'date', formatoptions: { newformat: 'm/d/Y' } },  //"formatter" and "formatoptions" is required for date sorting to works properly...
                         { name: 'RepairCost', index: 'RepairCost', sorttype: 'currency', width: 80, align: 'center', formatter: 'currency', formatoptions: { decimalSeparator: '.', thousandsSeparator: ',', decimalPlaces: 2, defaultValue: '0.00', prefix: '$', suffix: '' } },
                         { name: 'TotalCost', index: 'TotalCost', sorttype: 'currency', width: 80, align: 'center', formatter: 'currency', formatoptions: { decimalSeparator: '.', thousandsSeparator: ',', decimalPlaces: 2, defaultValue: '0.00', prefix: '$', suffix: '' } },
                         { name: 'DaysInInventory', index: 'DaysInInventory', sorttype: 'int', width: 65, align: 'center', formatter: 'number', formatoptions: { decimalSeparator: '', thousandsSeparator: ',', decimalPlaces: 0, defaultValue: '1' } },
                         { name: 'InventoryTrackerLocationId', index: 'InventoryTrackerLocationId', sorttype: 'int', width: 0, align: 'left', hidden: true, hidedlg: true },  //"hidedlg" is use to hide the hidden column in "Column Chooser"...
                         { name: 'InventoryTrackerLocation', index: 'InventoryTrackerLocation', sorttype: 'text', width: 120, align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
                         //Links is not present in json data from the website, so we customize it here...
                         { name: 'Links', index: 'Links', sorttype: 'text', width: 80, align: 'center', formatter: function (cellValue, options, rowObject) { return "&lt;span style='text-decoration:underline;cursor:pointer;'&gt;Links&lt;/span&gt;" }, search: false }  //"search" is use to hide the field in search dialog...
              ],
              beforeSelectRow: function (rowid, e) {
                  if (this.p.colModel[$.jgrid.getCellIndex($(e.target).closest("td")[0])].name === jqgridColumnNameLinks) {
                      jqgridPopupDialogLinkOptions(
                          $('#' + jqgridSpreadsheetId).getCell(rowid, jqgridColumnIdStockNumber),
                          $('#' + jqgridSpreadsheetId).getCell(rowid, jqgridColumnIdVin),
                          $('#' + jqgridSpreadsheetId).getCell(rowid, jqgridColumnIdInventoryTrackerLocationId)
                      );
                      return false;
                  }
              },
              pager: '#'+jqgridPagerId,
              rowNum: 10,
              rowList: [5, 10, 20, 50],  //Drop-down selection in footer - To show how many rows per page...
              //This "sortname"/"sortorder" must be specified for "getGridParam"'s 'datatype'/'sortname'/'sortorder' (column sorting) to work.  (Some kind of jqGrid bug or feature which we need to hack to do a workaround with)...
              &lt;% if(postQuickQuoteSalePrice.Length &gt; 0) { %&gt;
              sortname: 'TotalCost', sortorder: 'desc',  //Coming from Quick-Quote webpage...
              &lt;% }else{ %&gt;
              sortname: 'StockDate', sortorder: 'desc',  //Coming from any webpages...
              &lt;% } %&gt;
              viewrecords: true,
              //gridview: true,
              imgpath: '',
              caption: 'My Inventory',
              width: 1022,
              shrinkToFit: false,
              height: 400,
              sortable: true,  /* This allows both 1) Moving columns sideway to other location fields and 2) for jqGrid Column Chooser Plugin / JQuery Multiselect Plugin to work... */
              grouping: true,  /* This allows row data to be group into row grouping... */
              loadonce: true,  //In this case, use "sorttype" property in "colModel" for it to work when "loadonce" is set to true...
              emptyrecords: "No records to display",
              loadError: function (xhr, st, err) {
                  alert("An error had occurred, please try again or notify webmaster of this error");
              },
              loadComplete: function () {
                  var $self = $(this);  //This is needed to seperate itself from binding jqGrid or $(this) objects for it to work.  It wouldn't work without it...
                  if ($(this).jqGrid('getGridParam', 'datatype') === 'json') {  //This the value when loading webpage then the value of "datatype" option will become "local" afterward...
                      setTimeout(function () {
                          $self.triggerHandler("reloadGrid");
                      }, 50);
                  }
                  //jqgridSummarySpreadsheetDisplay();
              }
          });
  
          //jqGrid - My-Inventory-Summary...
          function jqgridSummarySpreadsheetDisplay() {
              $('#' + jqgridSummarySpreadsheetId).setCell(1, 'TotalVehicles', ($('#' + jqgridSpreadsheetId).getGridParam('records')), {'vertical-align':'middle'}, '', '');  //getGridParam('data').length)
              $('#' + jqgridSummarySpreadsheetId).setCell(1, 'TotalPurchaseCost', ($('#' + jqgridSpreadsheetId).getCol('PurchasePrice', false, 'sum')), { 'vertical-align': 'middle' }, '', '');
              $('#' + jqgridSummarySpreadsheetId).setCell(1, 'TotalRepairCost', ($('#' + jqgridSpreadsheetId).getCol('RepairCost', false, 'sum')), { 'vertical-align': 'middle' }, '', '');
              $('#' + jqgridSummarySpreadsheetId).setCell(1, 'TotalCost', ($('#' + jqgridSpreadsheetId).getCol('TotalCost', false, 'sum')), { 'vertical-align': 'middle' }, '', '');
          }
  
          //Navigation Buttons...
          //http://www.trirand.com/jqgridwiki/doku.php?id=wiki:navigator...
          //http://www.trirand.com/jqgridwiki/doku.php?id=wiki:custom_buttons...
          //This is required for "navButtonAdd" to appear...
          $('#'+jqgridSpreadsheetId).navGrid('#'+jqgridPagerId,
              { edit: false, add: false, del: false, search: true, view: false, refresh: false },  //Options...
              {}, //{edit}...
              {}, //{add}...
              {}, //{del}...
              {
                  multipleSearch: true, multipleGroup: false, closeOnEscape: true, closeAfterSearch: true, searchOnEnter: true, showQuery: false, width: 550, caption: "Search Records",
                  //overlay: 1,  //If overlay is set to 0, grid is disabled but if set to 1, grid is active and you can play with both search and grid at once.
                  afterRedraw: function () {
                      //Notice: May sure the "rule" drop-down selection is set to "all" by default...
                      $("input.add-rule", this).button().val("Add Rule");
                      $("input.delete-rule", this).button().val("Remove Rule");
                      $("select.opsel", this).hide();
                  }
              }, //{search}...
              {} //{view}...
          );
          //$('#'+jqgridSpreadsheetId).navSeparatorAdd('#'+jqgridPagerId, { sepclass: 'ui-separator', sepcontent: '' });  //Seperator bar icon...
          $('#'+jqgridSpreadsheetId).navButtonAdd('#'+jqgridPagerId, {
              position: "first",
              caption: "",
              buttonicon: "ui-icon-calculator",
              title: "Show Columns",
              //cursor: "pointer",  //This does not work...
              onClickButton: function () {
                  //http://www.trirand.com/jqgridwiki/doku.php?id=wiki:jquery_ui_methods&amp;s[]=column&amp;s[]=chooser...
                  $(this).columnChooser({
                      title: "Show Columns",
                      width: 600,
                      done: function (perm) {
                          if (perm) { //"OK" button are clicked...
                              this.jqGrid("remapColumns", perm, true);
                          //} else { //"Cancel" button or "x" button are clicked...
                          }
                      }
                  });
              }
          });
  
          //Columns Header Grouping...
          //[Drag a column]...
          $('tr.ui-jqgrid-labels th div').draggable({
              appendTo: 'body',
              helper: 'clone'
          });
          //[Drop a column]...
          $('#'+jqgridGroupColumnHeader+' ol').droppable({
              activeClass: 'ui-state-default',
              hoverClass: 'ui-state-hover',
              accept: ':not(.ui-sortable-helper)',
              drop: function (event, ui) {
                  var $this = $(this);
                  $this.find('.placeholder').remove();
                  var groupingColumn = $('&lt;li&gt;&lt;/li&gt;').attr('data-column', ui.draggable.attr('id').replace('jqgh_' + jqgridSpreadsheetId + '_', ''));
                  $('&lt;span class="ui-icon ui-icon-close"&gt;&lt;/span&gt;').click(function () {
                      $(this).parent().remove();
                      $('#' + jqgridSpreadsheetId).jqGrid('groupingRemove');
                     $('#'+jqgridSpreadsheetId).jqGrid('groupingGroupBy', $('#'+jqgridGroupColumnHeader+' ol li:not(.placeholder)').map(function () { return $(this).attr('data-column'); }).get());
                      //Make the text re-appear after the very last column is removed...
                      if ($('#'+jqgridGroupColumnHeader+' ol li:not(.placeholder)').length === 0) {
                          $('&lt;li class="placeholder"&gt;Drop header columns here&lt;/li&gt;').appendTo($this);
                      }
                  }).appendTo(groupingColumn);
                  groupingColumn.append(ui.draggable.text());
                  groupingColumn.appendTo($this);
                  $('#'+jqgridSpreadsheetId).jqGrid('groupingRemove');
                  $('#'+jqgridSpreadsheetId).jqGrid('groupingGroupBy', $('#'+jqgridGroupColumnHeader+' ol li:not(.placeholder)').map(function () { return $(this).attr('data-column'); }).get());
              }
          });
          //[Re-arrange columns' position in "Group Column Header" box]...
          $('#' + jqgridGroupColumnHeader + ' ol').sortable({
              items: 'li:not(.placeholder)',
              sort: function () {
                  $(this).removeClass('ui-state-default');
              },
              stop: function () {
                  $('#'+jqgridSpreadsheetId).jqGrid('groupingRemove');
                  $('#'+jqgridSpreadsheetId).jqGrid('groupingGroupBy', $('#'+jqgridGroupColumnHeader+' ol li:not(.placeholder)').map(function () { return $(this).attr('data-column'); }).get());
              }
              , revert: true
          });
  
          //Reposition the GUI stuff on browser resizing...
          $(window).resize(function () {
              $('#' + jqgridDialogLinkOptions).dialog("option", "position", "center");
          });
          //=====================================================================================================================================================================================================
          //=====================================================================================================================================================================================================
  
          //=====================================================================================================================================================================================================
          //=====================================================================================================================================================================================================
          //My Inventory Summary...
          //=====================================================================================================================================================================================================
          //=====================================================================================================================================================================================================
          //jqGrid Plugin...
          $('#' + jqgridSummarySpreadsheetId).jqGrid({
              datatype: 'jsonstring',  //'local',
              datastr: [{ "id": 1, "cell": ["", "", "", ""] }],  //It is surprising that it accepted blank values...
              colNames: ['Total Vehicles', 'Total Purchase Cost', 'Total Repair Cost', 'Total Cost'],  //Display Text in Column Header...
              colModel: [
                         //In this case, use "sorttype" property in "colModel" for it to work when "loadonce" is set to true...
                         { name: 'TotalVehicles', index: 'TotalVehicles', sorttype: 'int', align: 'center',  sortable: false, formatter: 'number', formatoptions: { decimalSeparator: '', thousandsSeparator: ',', decimalPlaces: 0, defaultValue: '' } },
                         { name: 'TotalPurchaseCost', index: 'TotalPurchaseCost', sorttype: 'currency', align: 'center', sortable: false, formatter: 'currency', formatoptions: { decimalSeparator: '.', thousandsSeparator: ',', decimalPlaces: 2, defaultValue: '', prefix: '$', suffix: '' } },
                         { name: 'TotalRepairCost', index: 'TotalRepairCost', sorttype: 'currency', align: 'center', sortable: false, formatter: 'currency', formatoptions: { decimalSeparator: '.', thousandsSeparator: ',', decimalPlaces: 2, defaultValue: '', prefix: '$', suffix: '' } },
                         { name: 'TotalCost', index: 'TotalCost', sorttype: 'currency', align: 'center', sortable: false, formatter: 'currency', formatoptions: { decimalSeparator: '.', thousandsSeparator: ',', decimalPlaces: 2, defaultValue: '', prefix: '$', suffix: '' } }
              ],
              caption: 'My Inventory Summary',
              width: 1022,
              shrinkToFit: true,
              height: '100%',
              loadonce: false,  //In this case, use "sorttype" property in "colModel" for it to work when "loadonce" is set to true...
              emptyrecords: "No records to display",
              loadError: function (xhr, st, err) {
                  alert("An error had occurred, please try again or notify webmaster of this error");
              }
          });
          //=====================================================================================================================================================================================================
          //=====================================================================================================================================================================================================
      });
  &lt;/script&gt; 
  
  &lt;div id="divWebLayout2" style="padding-top:2px;padding-bottom:20px;"&gt;
      &lt;div id="MyInventoryJqgrid_GroupColumnHeader"&gt;
           &lt;div class="ui-widget-content"&gt;&lt;ol&gt;&lt;li class="placeholder"&gt;Drop header columns here&lt;/li&gt;&lt;/ol&gt;&lt;/div&gt;
           &lt;div&gt;
               &lt;table id="MyInventoryJqgrid_Spreadsheet"&gt;&lt;/table&gt;
               &lt;div id="MyInventoryJqgrid_Pager" style="text-align:center;"&gt;&lt;/div&gt;
           &lt;/div&gt;
       &lt;/div&gt;
   &lt;/div&gt;
   &lt;div id="divWebLayout3" style="padding-bottom:20px;"&gt;
      &lt;table id="MyInventorySummaryJqgrid_Spreadsheet"&gt;&lt;/table&gt;
   &lt;/div&gt;
  </code></pre>