I was working on a Flex application in Flex 3 where I wanted to auto sort a column of a DataGrid component, which was populated dynamically (using PHP). I researched a lot and found a solution on the net.
DataGridColumn, when sorted manually, dispatches an event of type DataGridEvent. The simplest way that I found was to dispatch this even automatically through Action Script.
The Code Example
So we start off looking at a very simple DataGrid component that is coded below: -
<mx:DataGrid id="summary_dg" width="400" height="100%"> <mx:columns> <mx:DataGridColumn headerText="Project Keyword and Version" dataField="keyword_version"/> <mx:DataGridColumn headerText="Downloads" dataField="downloads" width="150"/> </mx:columns> </mx:DataGrid>
We shall now dispatch the sort event automatically using Action Script as shown below: -
summary_dg.dispatchEvent(new DataGridEvent(DataGridEvent.HEADER_RELEASE, false, true, 1, null, 0, null, null, 0));
Below is the syntax of this DataGridEvent() function: -
DataGridEvent(DataGridEvent.HEADER_RELEASE, bubbles, cancelable, columnIndex, currentTarget, dataField, itemRenderer, reason, rowIndex, target);
As you can see, the fourth parameter of new DataGridEvent() function is supposed to be the column index of the DataGrid, starting from 0.
Enhancements
The above code automatically sorts the desired column in Ascending Order. One question I needed answer for is – how to make it sort in descending order automatically?
Simplest way to do that is to specify the attribute sortDescending="true" for the specific <mx:DataGridColumn> tag. This attribute is just “default” sorting scheme and not permanent. Once the user clicks the column header again, it sorts in a different order. So, here is the code as per the current example.
I want the highest downloads to appear first. So, I specify this attribute to the 2nd column: -
<mx:DataGridColumn headerText="Downloads" dataField="downloads" width="150" sortDescending="true"/>
Hope you find this information useful.














Pingback: Flex DataGrid Auto Sort Example « Hemanth Sharma – Tech Blog
Pingback: Chen Yangjian's Blog» Blog Archive » Flex DataGrid Column 自动排序