Sorting a DataGrid on multiple columns
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
initialize="initDP();" width="550" height="400">
<mx:Script>
import mx.events.DataGridEvent;
import mx.collections.*;
private var myDPColl:ArrayCollection;
[Bindable]
private var sortA:Sort;
private var sortByColumn1:SortField;
private var sortByColumn2:SortField;
private var sortByColumn3:SortField;
private var myDP:Array = [{Column1:'A', Column2:'AA',Column3:11.99, Column4: true},
{Column1:'B', Column2:'BB',Column3:10.99, Column4: false},
{Column1:'C', Column2:'CC',Column3:12.99, Column4: true},
{Column1:'D', Column2:'VV',Column3:11.99, Column4: false},
{Column1:'E', Column2:'EE',Column3:11.99, Column4: true},
{Column1:'F', Column2:'FF',Column3:14.99, Column4: true},
{Column1:'G', Column2:'GG',Column3:5.99, Column4: true}
];
private function initDP():void {
myDPColl = new ArrayCollection(myDP);
sortA = new Sort();
sortByColumn1 = new SortField("Column1", true, true);
sortByColumn2 = new SortField("Column2", true);
sortByColumn3 = new SortField("Column3", true);
sortA.fields=[sortByColumn1, sortByColumn2];
myDPColl.sort=sortA;
myDPColl.refresh();
myGrid.dataProvider = myDPColl;
myGrid.rowCount = myDPColl.length +1;
}
private function headRelEvt(event:DataGridEvent):void {
sortA.fields[2] = sortA.fields[1];
sortA.fields[1] = sortA.fields[0];
if (event.columnIndex==0) {
sortA.fields[0] = sortByColumn1;
} else if (event.columnIndex==1) {
sortA.fields[0] = sortByColumn2;
} else {
sortA.fields[0] = sortByColumn3;}
myDPColl.sort = sortA;
myDPColl.refresh();
event.preventDefault();
}
</mx:Script>
<mx:DataGrid id="myGrid" width="100%" headerRelease="headRelEvt(event);">
<mx:columns>
<mx:DataGridColumn minWidth="120" dataField="Column1"/>
<mx:DataGridColumn minWidth="200" dataField="Column2"/>
<mx:DataGridColumn width="75" dataField="Column3"/>
</mx:columns>
</mx:DataGrid>
</mx:Application>
Related examples in the same category