Flex: Custom Sort DataGrid Column

Recently, I had to sort a column of data based on a number wrapped in parethesis.  Fortunately, there was an extra column being passed back from ColdFusion query that made this task simple.  Using the sortCompareFunction, I was able to sort on a datagrid column using a different column from my query or array collection.  There is some information out there on the subject, so this more just for my own reference than anything else.  

What my current column data looks like?

APL(35)
RNO(10)
LVG(15)

So basically I need to sort the datagrid column by the numbers inside of the parenthesis.  The extra column in my query contains those numbers. 

What does the code look like?

MXML:

<mx:DataGridColumn headerText="XX"
                                           dataField="OriginalQueryColumn"
                                           showDataTips="true"
                                           width="85"
                                           sortCompareFunction="from_sortCompare"
                                           />

AS:

protected function from_sortCompare(objA:Object, objB:Object):int
            {
                var Comp1:Number = objA.NumberQueryColumn;
                var Comp2:Number = objB.NumberQueryColumn;
                if(Comp1< Comp2) {
                    return -1;
                  } else if(Comp1== Comp2) {
                    return 0;
                  }
                  return 1;
            }

Its pretty simple, as you can see from the code above, the sortCompareFunction compares the numbers and returns -1,0,1 based on conditions and flex does the job of sorting the information.  If the extra column of data wasn't available; I would probably parse out the numbers and do it that way.

4 responses so far ↓

Stéphane - Apr 24, 2010 at 7:43 AM

Hello, attribute "sortCompareFunction" does not seem to be implemented in flex 2 and 3.2, what version of flex compiler are you using ?

Stephen Weyrick - Apr 24, 2010 at 12:36 PM

@Stephane

I'm was using flex 3.4 I think. Not sure if it was implemented in previous versions or not.

Stéphane - Apr 24, 2010 at 12:46 PM

It was, i was just getting troubles with my editor that did not want to compile according to this, your tip was already working in these version, thanks for sharing :)

Betty - Jun 4, 2010 at 5:32 AM

thanks

Leave a Comment