Filtering Data in Flex DataGrid
In the below example i used webservice to get data for the datagrid, thought this could also help
the begginners how to fetch data through webservice and display in datagrid…
Now coming to the code,Flex has the powerful method for filtering the data in ArrayCollection.
This can be done by assigning filterFunction to the arrayCollection.
<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute” creationComplete=”initApp()”>
<mx:Script>
<![CDATA[
import mx.rpc.soap.LoadEvent;
import mx.events.ListEvent;
import mx.controls.Alert;
import mx.collections.ArrayCollection;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
[Bindable]
private var gridData:ArrayCollection;
/* on creationComplete,the wsdl data is loaded */
private function initApp():void{
webService.wsdl = “http://www.abundanttech.com/WebServices/DeadOrAlive/DeadOrAlive.asmx?WSDL”;
webService.addEventListener(LoadEvent.LOAD,dataLoaded)
webService.loadWSDL();
}
/* once the dataloads,calling the particular method
of the webservice to get the particular data set*/
private function dataLoaded(e:LoadEvent):void{
webService.getTodaysBirthdays.send();
}
/* once we get the resultant data,the data assigned to the datgrid(this
is an simple example for getting data from webservice) */
private function resultHandler(e:ResultEvent):void{
gridData = ArrayCollection(e.result.Tables.Table.Rows);
total.text = gridData.length.toString();
}
/*
Here once the refresh method called,
Flex passes the each row data into the (applyFilter)function as an object
*/
private function filterGrid():void{
gridData.filterFunction = applyFilter;
gridData.refresh()
total.text = gridData.length.toString();
}
/* This is the important function where
we need to put our logic for filtering the data
For True – the row value is displayed
For False – the row value is filtered*/
private function applyFilter(item:Object):Boolean{
if(minAge.text <= item.Age && item.Age <= maxAge.text )
return true;
else
return false;
}
/* Reseting the data is simple,since we are not deleting at anystage,
the data will always remains in the memory */
private function resetData():void{
gridData.filterFunction = null;
gridData.refresh()
total.text = gridData.length.toString();
minAge.text = ”;
maxAge.text = ”;
}
]]>
</mx:Script>
<mx:WebService id=”webService” result=”resultHandler(event)” />
<mx:DataGrid id=”dg” x=”10″ y=”124″ width=”498″ height=”274″ dataProvider=”{gridData}” />
<mx:Label x=”147″ y=”61″ text=”Min Age:”/>
<mx:Label x=”147″ y=”98″ width=”95″ text=”No of Persons:”/>
<mx:Text x=”253.5″ y=”98″ width=”124″ id=”total”/>
<mx:Label x=”277″ y=”61″ text=”Max Age:”/>
<mx:Button x=”389″ y=”59″ label=”Filter” click=”filterGrid()”/>
<mx:TextInput x=”209″ y=”59″ width=”33″ height=”20″ id=”minAge”/>
<mx:TextInput x=”343″ y=”59″ width=”29.5″ id=”maxAge”/>
<mx:Button label=”Reset” click=”resetData()” x=”389″ y=”96″/>
</mx:Application>