I want to display total sum of rows values in an arraycollection. For example:
Definition Value
Product 1 20.00
Product 2 50.00
Product 3 30.00
Total 100.00
I have this code:
<mx:DataGrid id="srcgrid">
<mx:columns>
<mx:DataGridColumn dataField="Definition"/>
<mx:DataGridColumn dataField="Value"/>
</mx:columns>
</mx:DataGrid>
<s:Form>
<s:FormItem label="Total">
<s:Label text="{total()}"/>
</s:FormItem>
</s:Form>
And the script:
public function total():String {
var i:Number = 0;
for each(var obj:Object in ArrayCollection(DataGrid(srcgrid).dataProvider)){
i = i + obj.Value;
}
return i.toString();
}
Any idea?
Thanks in advance
The total()
function was called before there was anything inside the dataProvider
.
Also srcgrid.dataProvider
can be looped as an Object
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" applicationComplete="addInitData(event)">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<mx:DataGrid id="srcgrid">
<mx:columns>
<mx:DataGridColumn dataField="Definition"/>
<mx:DataGridColumn dataField="Value"/>
</mx:columns>
</mx:DataGrid>
<s:Form x="250">
<s:FormItem label="Total">
<s:Label id="total"/>
</s:FormItem>
</s:Form>
<fx:Script>
<![CDATA[
import flash.events.Event;
import mx.collections.ArrayList;
private function addInitData(e:Event = null):void{
var dataProvider:ArrayList = new ArrayList();
for (var i:int = 0; i < 12; i++){
dataProvider.addItem({Definition : 'item_' + i, Value : i});
}
srcgrid.dataProvider = dataProvider;
updTotal();
}
private function updTotal():void{
var sum:Number = 0;
for (var k:String in srcgrid.dataProvider){
sum += srcgrid.dataProvider[k]['Value'];
}
total.text = sum.toString();
}
]]>
</fx:Script>
</s:Application>