May 11 2004

Flex MXML Sample 1: adding a calculated column to a datagrid

Published by at 13:24 under Wayback Archive

Today I was asked how one gives cells in a column of a DataGrid a calculated value, based on other values in the same row. There are several options that you can choose from, but the most easy one is specifying a labelFunction for a new column. In the extended entry I have posted the sample source code, I hope it’s usefull.

Screenshot of sample MXML application

<mx:Application xmlns:mx=”http://www.macromedia.com/2003/mxml” width=”400″ height=”300″>
 <mx:CurrencyFormatter id=”PriceFormatter”
  precision=”2″
  decimalSeparatorTo=”.”
  currencySymbol=””
  alignSymbol=”left”
 />
 
 <mx:Script>
  <![CDATA[
   function formatPrice(item):String {
    return PriceFormatter.format(item.Price);
   }
   
   function calculateTotal(item):String {
    var sum = item.Price * item.Amount;
    return isNaN(sum) ? “” : PriceFormatter.format(sum.toString());
   }
  ]]>
 </mx:Script>
 
 <mx:DataGrid editable=”true” widthFlex=”1″ heightFlex=”1″>
  <mx:dataProvider>
   <mx:Array>
    <mx:Object>
     <Artist>Stevie Wonder</Artist>
     <Price>10.995</Price>
     <Album>The Definitive Collection</Album>
     <Amount>2</Amount>
    </mx:Object>
    <mx:Object>
     <Artist>Stevie Wonder</Artist>
     <Album>Songs in the Key of Life</Album>
     <Price>26.99</Price>
     <Amount>4</Amount>
    </mx:Object>
    <mx:Object>
     <Artist>Stevie Wonder</Artist>
     <Album>Innervisions</Album>
     <Price>13.99</Price>
     <Amount>1</Amount>
    </mx:Object>
   </mx:Array>
  </mx:dataProvider>
  
  <mx:columns>
   <mx:Array>
    <mx:DataGridColumn columnName=”Album” editable=”false” width=”150″ />
    <mx:DataGridColumn columnName=”Price” editable=”false” labelFunction=”formatPrice” width=”60″ />
    <mx:DataGridColumn columnName=”Amount” width=”60″ />
    <mx:DataGridColumn headerText=”Sum” editable=”false” labelFunction=”calculateTotal” width=”60″ />
   </mx:Array>
  </mx:columns>
 </mx:DataGrid>
</mx:Application>

3 responses so far

3 Responses to “Flex MXML Sample 1: adding a calculated column to a datagrid”

  1. Sudhakar says:

    Hi ,
    I’m new to Flex .Could some one tell me how to create a DataGrid with 25 Columns.

    I have some 500 datas in an xml file ,i have to bring these data in the datagrid of 25*20.

    awaiting for the earliest reply !!!

  2. Waldo Smeets says:

    The sample on how to do this can be found in the Flex documentation. However, much more important is the question whether you really should do this. I mean, 25 columns is a whole lot of data to be shown on the screen. Wouldn’t it be better to go for another way of presenting this data? Like a grid for the overview with just a few columns, and then a detailed view for the rest?