Sorting numeric values in a Flex DataGrid
When loading data from a webservice to be shown in a datagrid it seemed that all values in the grid are treated as string-values. So when sorting numeric columns the values were not in the correct order.
Instead of:
1 - 2 - 3 - 4 - 11 - 12 -21
You get:
1 - 11 - 12 - 2 - 21 - 3 - 4
But there is an easy solution: give the numeric column a “sortCompareFunction”. This function enables you to give this column a custom sort order.
This is the code of the example:
private function sortNumeric(obj1:Object, obj2:Object):int {
var value1:Number = (obj1.testvalue == '' || obj1.testvalue == null) ? null : new Number(obj1.testvalue);
var value2:Number = (obj2.testvalue == '' || obj2.testvalue == null) ? null : new Number(obj2.testvalue);
if (value1 < value2) { return -1; } else if (value1 > value2) {
return 1;
} else {
return 0;
}
}