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.
October 1st, 2009








7:54 pm on November 9th, 2009
This was useful to me. Thanks!
6:17 pm on January 6th, 2010
wonderful !!
7:18 pm on March 17th, 2010
hey i think the answer to my problems is in your post but i dont understant how to use your function… i tried creating a function and dispatching an event but i have can you show me a little demo or what the function should actually look like?
8:43 pm on March 17th, 2010
[...] post is just an extension of my earlier post describing the auto sort solution for your Flex DataGrid. Upon request, I have built a simple code [...]
8:44 pm on March 17th, 2010
@miguel, Please find the new post I just published to demonstrate this with an example. Find it here: -
http://www.hsharma.com/tech/adobe/flex-datagrid-auto-sort-example