Header Ad

Tuesday, July 9, 2013

Sorting numeric data having comma seperated values in Adobe Flex?

The following example which is having numeric data with comma(s) for one of the grid column. We need to handle specially in order to sort
this datagrid column where the data is having comma values.

We will use sortCompare function for the datagrid column which is having comma seperated numeric values. This sortCompare function will have
the code for removing comma's from numeric data and performs the sort functionality.

The following sample example with complete implementation.


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" >
        <mx:XMLList id="testdata">
        <testdata> <name>a</name> <testvalue>1,20,000.00</testvalue> </testdata>
        <testdata> <name>aa</name> <testvalue>1,100.00</testvalue> </testdata>
        <testdata> <name>ab</name> <testvalue>1,20,300.00</testvalue> </testdata>
        <testdata> <name>b</name> <testvalue>2</testvalue> </testdata>
        <testdata> <name>ba</name> <testvalue>21.00</testvalue> </testdata>
        <testdata> <name>bb</name> <testvalue>22</testvalue> </testdata>
        <testdata> <name>c</name> <testvalue>3.00</testvalue> </testdata>
        <testdata> <name>d</name> <testvalue>4</testvalue> </testdata>
        <testdata> <name>e</name> <testvalue>5</testvalue> </testdata>
        <testdata> <name>f</name> <testvalue>6</testvalue> </testdata>
        <testdata> <name>g</name> <testvalue>7</testvalue> </testdata>
    </mx:XMLList>
    <mx:Script>
        <![CDATA[
            import mx.collections.ArrayCollection;
            import mx.collections.Sort;
            import mx.collections.SortField;
            import mx.events.FlexEvent;
            private function sortNumeric(obj1:Object, obj2:Object):int {
                var regExpr:RegExp = /,/g;
                var value1:String = obj1.testvalue;
                var value2:String = obj2.testvalue;
                value1 = value1.replace(regExpr,"");
                value2 = value2.replace(regExpr,"");
           
                if (Number(value1) < Number(value2)) {
                    return -1;
                } else if (Number(value1) > Number(value2)) {
                    return 1;
                } else {
                    return 0;
                }
            }
           
           
           
        ]]>
    </mx:Script>
    <mx:DataGrid x="10" y="10" dataProvider="{testdata}" id="dgTest" width="400" height="300">
        <mx:columns>
            <mx:DataGridColumn headerText="Text" dataField="name" />
            <mx:DataGridColumn headerText="Number as Text" dataField="testvalue" />
            <mx:DataGridColumn headerText="Number as Number" dataField="testvalue" sortCompareFunction="sortNumeric" />
        </mx:columns>
    </mx:DataGrid>
   

</mx:Application>

No comments: