I have a Spark DataGrid with columns for price and location for a list of products. How do I sort the rows by location, and then by price? Both are simple text fields.
i have used SortField and Sort. I have created two way to sort the column in datagrid.
I have used sorting depends on the column click.
On click of location column I have used only that column data sorting.
When clicking on price column it sorts both columns.
I have attached two sample files for sorting the data in the datagrid.
Example : Using SDK 4.5
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
creationComplete="application1_creationCompleteHandler(event)">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.collections.Sort;
import mx.collections.SortField;
import mx.events.FlexEvent;
import spark.events.GridEvent;
private var dataProvider : ArrayCollection = new ArrayCollection(
[{price:"20",location:"india"},
{price:"5",location:"india"},
{price:"40",location:"india"},
{price:"20",location:"germeny"},
{price:"20",location:"spain"},
{price:"10",location:"usa"},
{price:"30",location:"Italy"}]);
private var bool : Boolean = false;
protected function dg_clickHandler(event:GridEvent):void
{
///////////////////////////////////////// use this for individul column click sorting//////////////////////
var sort : Sort = new Sort();
if(event.columnIndex == 1)
{
var locSort : SortField = new SortField("location",true,bool);
sort.fields = [locSort];
}
else
{
var locSort : SortField = new SortField("location",true,bool);
var priceSort : SortField = new SortField("price",false,bool,true);
sort.fields = [locSort,priceSort];
}
dataProvider.sort = sort;
dataProvider.refresh();
bool = !bool;
//////////////////////////////////////////////// combine sorting end////////////////////////////////////////////
/////////////////////////////////////////////// use this for combine sorting////////////////////////////////
var locSort : SortField = new SortField("location",true,bool);
var priceSort : SortField = new SortField("price",false,bool,true);
var sort : Sort = new Sort();
sort.fields = [locSort,priceSort];
dataProvider.sort = sort;
dataProvider.refresh();
bool = !bool;
/////////////////////////////////////////individul sorting end//////////////////////////////////////////////
}
protected function application1_creationCompleteHandler(event:FlexEvent):void
{
dg.columnHeaderGroup.addEventListener(GridEvent.GRID_CLICK, dg_clickHandler);
}
]]>
</fx:Script>
<s:DataGrid id="dg" width="100%" dataProvider="{dataProvider}">
<s:columns>
<s:ArrayList>
<s:GridColumn headerText="Price" dataField="price" />
<s:GridColumn headerText="Location" dataField="location"/>
</s:ArrayList>
</s:columns>
</s:DataGrid>
</s:Application>
+