Numeric sorting of Flex DataGridColumn
Utorok, November 3rd, 2009Table of contents for flex-tips
- Problem with XML attributes in AS3.0
- Unable to export SWC oem
- Numeric sorting of Flex DataGridColumn
This is quick example for Numeric sorting of Flex DataGrid columns. If you want to sort column in DataGrid, default sorting is sorted by String and not by Number. If you have just one numeric column, you may create custom sort function and set sortCompareFunction for given DataGridColumn. If you have more such columns and your dataProvider is ArrayCollection, which consists of many objects, better solution is override DataGridColumn and implement compare function inside this class. Here is class
package com.flexets.components.dataGridClasses { import mx.controls.dataGridClasses.DataGridColumn; import mx.utils.ObjectUtil; public class NumericDataGridColumn extends DataGridColumn { public static const NUMERIC:String = "N"; public function NumericDataGridColumn(columnName:String=null) { super(columnName); initCompare(NUMERIC); } function initCompare(numeric:Object):void { if (numeric == NUMERIC) { sortCompareFunction = numericCompare; } } /** * Pull the numbers from the objects and call the implementation. TAKEN FROM mx.collections.SortField */ private function numericCompare(a:Object, b:Object):int { var fa:Number; try { fa = dataField == null ? Number(a) : Number(a[dataField]); } catch(error:Error) { } var fb:Number; try { fb = dataField == null ? Number(b) : Number(b[dataField]); } catch(error:Error) { } return ObjectUtil.numericCompare(fa, fb); } } }
and then just use NumericDataGridColumn in your mxml in DataGrid like this
<mx:DataGrid id="myDG" width="100%" height="100%" dataProvider="{myDataProvider}"> <mx:columns> <mx:DataGridColumn dataField="id"/> <dataGridClasses:NumericDataGridColumn dataField="order"/> <mx:DataGridColumn dataField="title"/> <dataGridClasses:NumericDataGridColumn dataField="price"/> </mx:columns> </mx:DataGrid>
Enjoy this little Flex tip.
1 Trackbacks/Pingbacks
2 Comments
Arturas
• Visit Site
November 10th, 2009
We’ve also experienced similar problems while developing our pivot table component. Check it out you should find it interesting, maybe you would like to write a blog post about our component? I’d gladly answer your questions and provide any additional info.
Flexmonster
noname
• Visit Site
Január 3rd, 2010
this is just what i was looking for…
but can’t get it to work. (i’m a newbie/hacker)
a complete example would have been idea.
thx.
Sorry, comments for this entry are closed at this time.