View comments | RSS feed

Sorting data in DataGrid controls

The DataGrid control supports displaying sorted data in two ways:

For detailed information on using the Sort and SortField classes, see Sorting and filtering data for viewing.

Subtopics

Determining the initial DataGrid sort order
Controlling user sorting of DataGrid displays
Example: Sorting a DataGrid on multiple columns

Determining the initial DataGrid sort order

To specify the initial DataGrid sort order, you sort the data provider. While a number of approaches can work, the following technique takes best advantage of the built in features of Flex collections:

Controlling user sorting of DataGrid displays

Three DataGrid and DataGridColumn properties control how users can sort the order of a data

By default, the DataGrid class uses its own sort code to control how the data gets sorted when the user clicks a column. To override this behavior, you create a headerRelease event handler to handle the DataGridEvent class event that is generated when the user clicks the column header. This event handler must do the following:

  1. Use the event object's columnIndex property to determine the clicked column.
  2. Establish a Sort object with a set of SortField objects based on the clicked column and any other rules that you need to control the sorting order.
  3. Apply the Sort object to the data provider ICollectionView.
  4. Call the DataGridEvent class event object's preventDefault() method to prevent the DataGrid from doing a default column sort.

NOTE

 

If you specify a labelFunction property, you must also specify a sortCompareFunction function. The Computed Columns example in Flex Explorer shows this use.

The following example shows how to use the headerRelease event handler to do multi-column sorting when a user clicks a DataGrid column header.

Example: Sorting a DataGrid on multiple columns

The following example shows how you can use a collection with a Sort object to determine an initial multi-column sort and to control how the columns sort when you click the headers. The data grid is initially sorted by in-stock status first, artist second, and album name, third. If you click any heading, that column becomes the primary sort criterion, the previous primary criterion becomes the second criterion, and the previous secondary criterion becomes the third criterion.

<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        initialize="initDP();" width="550" height="400">
        
    <mx:Script>
        <![CDATA[
            import mx.events.DataGridEvent;
            import mx.collections.*;
            
            // Declare storage variables and initialize the simple variables.
            // The data provider collection.
            private var myDPColl:ArrayCollection;
            // The Sort object used to sort the collection.
            private var sortA:Sort;
            // The sort fields used to determine the sort.
             private var sortByInStock:SortField;
             private var sortByArtist:SortField;
             private var sortByAlbum:SortField;
             private var sortByPrice:SortField;
            // The data source that populates the collection.
            private var myDP:Array = [
                {Artist:'Pavement', Album:'Slanted and Enchanted', 
                    Price:11.99, InStock: true},
                {Artist:'Pavement', Album:'Crooked Rain, Crooked Rain', 
                    Price:10.99, InStock: false},
                {Artist:'Pavement', Album:'Wowee Zowee', 
                    Price:12.99, InStock: true},
                {Artist:'Asphalt', Album:'Brighten the Corners', 
                    Price:11.99, InStock: false},
                {Artist:'Asphalt', Album:'Terror Twilight', 
                    Price:11.99, InStock: true},
                {Artist:'Asphalt', Album:'Buildings Meet the Sky', 
                    Price:14.99, InStock: true},
                {Artist:'Other', Album:'Other', Price:5.99, InStock: true}
            ];

            //Initialize the DataGrid control with sorted data.
            private function initDP():void {
                //Create an ArrayCollection backed by the myDP array of data.
                myDPColl = new ArrayCollection(myDP);
                //Create a Sort object to sort the ArrrayCollection.
                sortA = new Sort();
                //Initialize SortField objects for all valid sort fields:
                // A true second parameter specifies a case-insensitive sort.
                // A true third parameter specifies descending sort order.
                // A true fourth parameter specifies a numeric sort.
                 sortByInStock = new SortField("InStock", true, true);
                 sortByArtist = new SortField("Artist", true);
                 sortByAlbum = new SortField("Album", true);
                 sortByPrice = new SortField("Price", true, false, true);
                // Sort the grid using the InStock, Artist, and Album fields.
                sortA.fields=[sortByInStock, sortByArtist, sortByAlbum];
                myDPColl.sort=sortA;
                // Refresh the collection view to show the sort.
                myDPColl.refresh();
                // Set the ArrayCollection as the DataGrid data provider.
                myGrid.dataProvider=myDPColl;
                // Set the DataGrid row count to the array length, 
                // plus one for the header.
                myGrid.rowCount=myDPColl.length +1; 
            }    
        
            // Re-sort the DataGrid control when the user clicks a header.
            private function headRelEvt(event:DataGridEvent):void {
                // The new third priority was the old second priority.
                sortA.fields[2] = sortA.fields[1];
                // The new second priority was the old first priority.
                sortA.fields[1] = sortA.fields[0];
                // The clicked column determines the new first priority.
                if (event.columnIndex==0) {
                    sortA.fields[0] = sortByArtist;
                } else if (event.columnIndex==1) {
                    sortA.fields[0] = sortByAlbum;
                } else if (event.columnIndex==2) {
                    sortA.fields[0] = sortByPrice;
                } else {
                    sortA.fields[0] = sortByInStock;}
                // Apply the updated sort fields and re-sort.
                myDPColl.sort=sortA;
                // Refresh the collection to show the sort in the grid.
                myDPColl.refresh();
                // Prevent the DataGrid from doing a default column sort.
                event.preventDefault();
            }
        ]]>
    </mx:Script>

    <!-- The Data Grid control. 
            By default the grid and its columns can be sorted by clicking. 
            The headerRelease event handler overrides the default sort
            behavior. -->
    <mx:DataGrid id="myGrid" width="100%" headerRelease="headRelEvt(event);">
        <mx:columns>
                <mx:DataGridColumn minWidth="120" dataField="Artist" />
                <mx:DataGridColumn minWidth="200" dataField="Album" />
                <mx:DataGridColumn width="75" dataField="Price" />
                <mx:DataGridColumn width="75" dataField="InStock"
                    headerText="In Stock"/>
        </mx:columns>
    </mx:DataGrid>
</mx:Application> 

Flex 2

Comments


ambrishmisra said on Nov 1, 2006 at 1:22 PM :
This example seems to be somewhat broken. Although functionality works, but one of the graphical ques which denotes that sorting is asc/desc is missing.

The sort arrow (one available in the header, specifying asc/desc sort by showing a small arrow) is missing in this case.

 

RSS feed | Send me an e-mail when comments are added to this page | Comment Report

Current page: http://livedocs.adobe.com/flex/2/docs/00000598.html