Sorting and the DataGrid component

Another Tuesday LiveDocs day! The following example continues the theme of DataGrids and sorting.

The following example sorts columns either numerically or alphabetically. By default columns are sorted alphanumerically, so if you had a DataGrid with “1, 213, 11, 7″ it would sort as “1,11,213,7″. By writing a custom sorting function that uses Array.sortOn, you can sort the dataProvider yourself using a numeric or text sort (even sort text as case insensitive).

1. Make sure you have DataGrid in Library
2. Add following ActionScript to frame 1 of the Timeline:

import mx.controls.gridclasses.DataGridColumn;
var my_dp:Array = new Array({name:’Grissom, M.’, avg:0.279}, {name:’Bonds, B.’, avg:0.362}, {name:’Cruz, D.’, avg:0.292}, {name:’Snow, J.’, avg:0.327});
var dg = this.createClassObject(mx.controls.DataGrid, “my_dg”, 999, {dataProvider:my_dp});
dg.setSize(240, 180);
var name_dgc:DataGridColumn = new DataGridColumn(“name”);
name_dgc.headerText = “Name:”;
name_dgc.width = 160;
var avg_dgc:DataGridColumn = new DataGridColumn(“avg”);
avg_dgc.headerText = “Avg:”;
avg_dgc.width = 60;
var myListener:Object = new Object();
myListener.headerRelease = function(evt:Object) {
var sortOrder:String =;
var sortColumn:String =[evt.columnIndex];
switch (sortColumn) {
case ‘name’ :
sortArray(my_dp, sortColumn, “TEXTNOCASE”, sortOrder);
case ‘avg’ :
sortArray(my_dp, sortColumn, “NUMERIC”, sortOrder);
my_dg.addEventListener(“headerRelease”, myListener);
function sortArray(my_array:Array, sortColumn:String, sortType:String, sortOrder:String) {
var sortOptions:Number = 0;
switch (sortType.toUpperCase()) {
case ‘NUMERIC’ :
sortOptions |= Array.NUMERIC;
sortOptions |= Array.CASEINSENSITIVE;
if (sortOrder.toUpperCase() == ‘DESC’) {
sortOptions |= Array.DESCENDING;
my_array.sortOn(sortColumn, sortOptions);

3. Format the code (press the Auto Format button).
4. Test.