December 11th, 2007 by Kyle
Tags: arraycollection, bytearray, clone, collection, datagrid, Flex, mxml, sort, sorted
Posted in: Flex
I had a customer asking how to do this.
Sorting the datagrid sorts the underlying dataprovider.
Remember that things like ArrayCollections are just essentially views of the data. So adding an element to the underlying data, regardless of the position at which you add the new item, will not affect its position in the “view”. It will get added in its sorted position if the view is showing sorted data. The workaround to this is show in the simple sample below:
<mx:application xmlns:mx="http://www.adobe.com/2006/mxml" creationcomplete="init()">
<mx:script>
<!–[CDATA[
import mx.collections.ArrayCollection;
public var objs:ArrayCollection = new ArrayCollection();
/*
* initialize the dataprovider
*/
private function init():void {
var obj:Object = new Object();
obj.name = "carry";
objs.addItem(obj);
obj = new Object();
obj.name = "fred";
objs.addItem(obj);
obj = new Object();
obj.name = "henry";
objs.addItem(obj);
obj = new Object();
obj.name = "issac";
objs.addItem(obj);
obj = new Object();
obj.name = "mary";
objs.addItem(obj);
obj = new Object();
obj.name = "tom";
objs.addItem(obj);
obj = new Object();
obj.name = "tom2";
objs.addItem(obj);
dg.dataProvider = objs;
}
import flash.utils.ByteArray;
private function clone(source:Object):*
{
var myBA:ByteArray = new ByteArray();
myBA.writeObject(source);
myBA.position = 0;
return(myBA.readObject());
}
private function addObj():void{
var temp:Array = clone(objs.toArray());
objs=new ArrayCollection(temp);
dg.dataProvider=objs;
var obj:Object = new Object();
obj.name=”;
objs.addItemAt(obj, 0);
}
]]–>
</mx:script>
<mx:button width="150" label="Add New Row" click="addObj()">
<mx:datagrid id="dg" editable="true" width="50%" height="80%">
<mx:columns>
<mx:datagridcolumn headertext="Name" datafield="name">
editable="true" />
</mx:datagridcolumn>
</mx:columns>
</mx:datagrid>
</mx:button></mx:application>
Browse the source of this example.
Download a zipfile containing the source to this sample.
2 Comments »

Recent Comments