Datagrid calculation

hai
i have one problem i want to add two column values and display sum of the value into thired column in the data grid
the two column value taken from external XML File

Hi.
Alex has some examples of how to make footers for DataGrids on his blog, you might find this interesting:
http://blogs.adobe.com/aharui/2007/04/datagrid_footers.html
http://blogs.adobe.com/aharui/2008/03/flex_3_datagrid_footers.html

Similar Messages

  • Direction Needed: Storing calculated values from datagrid column in order to call values into graph

    Hi all,
    I am new to Flex/Flash Builder, actionscript, and mxml, so please be kind.
    I have developed a small program that has a component that displays a datagrid fed with information out of a mysql db via a php data services connection. Within that same component (page), I have a graph that charts the dates via a plot chart. I am interested in adding a line series to the graph, but the data I want to use is a calculated field in the datagrid which I used a custom lable function to derive and display. Can someone steer me to the correct method to store such values and how to call them into a chart?
    Some addition information
    Custom label function:
      /* Custom label function for the Delta1 column. Calculates the number of days between the planting date and 10% flower. */
                                  private function calculateTo1stFlower(item:Object, column:GridColumn):String {
                                            var tempDate1:Date = new Date(item.dflower10 - item.dplanting);
                                            return Math.round((tempDate1.time / MS_PER_DAY) + 1).toString();
    /* Number of milliseconds in a day. (1000 milliseconds per second * 60 seconds per minute * 60 minutes per hour * 24 hours per day) */
                                  private const MS_PER_DAY:uint = 1000 * 60 * 60 * 24;
    Within my spark datagrid
    <s:GridColumn width="30" headerText="Δ1" labelFunction="calculateTo1stFlower" ></s:GridColumn>
    I assume I need to store the array of values for this column and then chart the saved values as the xField within the LineSeries. Should I use a class based model?
    The following link seemed like it may be an appropriate path; I am not sure though.
    http://help.adobe.com/en_US/flex/using/WS2db454920e96a9e51e63e3d11c0bf69084-7b51.html
    Thanks in advance for any support,
    Matthew

    Thanks for trying to post DDL, but you have no idea how to do a data model. You do not know that tables have to have keys, what ISO-11179 is, etc. 
    You have a table that is supposed to model companies. Your singular names says that there is only one company!  There is no company identifier (the industry standard is the DUNS). A customer is not a company. We do not use numeric data types for identifiers;
    do you do math on them? NO!  The attribute property comes after the attribute name (you never heard of ISO-11179). 
    Think about how silly VARCHAR(1) is. 
    CREATE TABLE Companies 
    (company_duns CHAR(9) NOT NULL PRIMARY KEY, 
     company_name VARCHAR(30)NOIT NULL, 
     margin_oil INTEGER NOT NULL, 
     margin_hangar INTEGER NOT NULL, 
     margin_cleaning INTEGER NOT NULL);
    INSERT INTO Companies
     VALUES (1, 'AviatKorea', 100, 125, 200), 
    (2, 'AXHollande', 50, 40, 30), 
    (3, 'BFXNorway', 60, 80, 600), 
    (4, 'EEEFrance', 10, 25, 60);
    CREATE TABLE Company_Tariffs
    (company_duns INTEGER NOT NULL
       REFERENCES Companies(company_duns), 
     tariff_type CHAR(1) NOT NULL
        CHECK (tariff_type IN ('A','B','C','D'),
     PRIMARY KEY (company_duns, tariff_type));
    INSERT INTO Company_Tariffs values (1, 'A'), (2, 'C'), (2, 'D'), (3, 'A'), (4, 'A'), (4, 'C'), (4, 'D')
    SELECT * -- do not use * in production code
      FROM Companies AS C,
           Company_Tariffs AS T 
     WHERE C.company_duns = T.company_duns;
    >> I would like something like with a computed column [ ] that retrieves the different contracts used: <<
    You might but a SQL programmer would not. This violated First Normal Form. It is a display report and is done in the presentation layers. 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Datagrid with calculated column

    Hi all,
    Does anyone know how or where I might learn to create a
    calculated field in a DataGrid?
    Flex 2

    There are several ways, depending on what you want.
    Easiest is to use a labelFunction() instead of a dataField.
    A custom item renderer is another way.
    Yet a third way is to have your dataProvider be a collection
    of custom value objects, one of which is the calculated value.
    Tracy

  • Is it possible to use the same calculations in another frame. Or maybe another solution.

    Hello everyone.
    Sorry to bother you again. As you have probably have seen before  I am working on a calculator. I ran into another problem as i want to add some more features to the calculator i already made.
    The problem is this:
    I have included a checkbox. That checkbox has to enable and disable a drop down box and 2 sliders. And when they are enabled they
    have to make a 2nd calculation beside the 1st calculation. But they need to use parts of the 1st calculation. How can i implement
    this without messing with the first script?
    I tried to make the long script easier readable with the colors. I hope someone can help.
    import fl.controls.ComboBox
    import fl.controls.Slider
    import fl.controls.DataGrid
    import fl.controls.dataGridClasses.DataGridColumn
    import fl.data.DataProvider
    var levelArray:Array=new Array("disastrous","wretched","poor","weak","inadequate","passable","solid","excellent"," formidable","outstanding","brilliant","magnificent","worldclass","supernatural","titanic", "extra-terrestrial","mythical","magical","utopian","divine")
    var trainingArray:Array=new Array("Goalkeeping","Defending","Defensive Positions","Crossing","WingAttack","Playmaking","Scoring","Shooting","Short Passes","Through Passes","Set Pieces")
    var trainingBase:Array=new Array(3.0206,5.4824,10.9648,3.2341,5.3902,4.6613,4.8536,8.0893,4.2989,5.0575,0.9938)
    // years slide
    yearsSb.addEventListener(Event.CHANGE,onYearsChange)
    // days slide
    daysSb.addEventListener(Event.CHANGE,onDaysChange)
    // Current skill slide
    skillminSb.addEventListener(Event.CHANGE,onMinSkilChange)
    // To skill slide
    skillmaxSb.addEventListener(Event.CHANGE,onMaxSkilChange)
    // sublevel slide
    subSb.addEventListener(Event.CHANGE,onSubChange);
    // coach slide
    coachSb.addEventListener(Event.CHANGE,onCoachChange)
    // assistans slide
    assSb.addEventListener(Event.CHANGE,onAssChange)
    // intensity slide
    intensitySb.addEventListener(Event.CHANGE,onIntensityChange)
    // stamina slide
    staminaSb.addEventListener(Event.CHANGE,onStaminaChange)
    for (var i=0;i<trainingArray.length;i++){
              trainingCb.addItem({label:trainingArray[i], data:trainingBase[i]})
    trainingCb.addEventListener(Event.CHANGE,changeEvent)
    trainingCb.selectedIndex=0
    // datagrid
    //dg.columns = ["Week", "Skill", "Length", "Age" ];
    var weekCol:DataGridColumn=new DataGridColumn()
    weekCol.dataField="Week"
    weekCol.sortOptions = Array.NUMERIC;
    weekCol.width=50
    dg.addColumn(weekCol)
    var skillCol:DataGridColumn=new DataGridColumn()
    skillCol.dataField="Skill"
    skillCol.width=150
    skillCol.sortOptions = Array.NUMERIC;
    dg.addColumn(skillCol)
    var lengthCol:DataGridColumn=new DataGridColumn()
    lengthCol.dataField="Length"
    lengthCol.width=75
    dg.addColumn(lengthCol)
    var ageCol:DataGridColumn=new DataGridColumn()
    ageCol.dataField="Age"
    ageCol.width=75
    dg.addColumn(ageCol)
    // variables
    var years:Number
    var days:Number
    var yearsFactor:Number
    var level:Number
    var subLevel:Number
    var levelFactor:Number
    var trainingFactor:Number
    var coachFactor:Number
    var assistentsFactor:Number
    var intensity:Number
    var stamina:Number
    var weeks:Number
    var skillUp:Number
    var baseLevel:Number
    var newLevel:Number
    var skillDown:Number
    // initialise graph mc
    var graphMc:MovieClip=new MovieClip()
    graphMc.x=80
    graphMc.y=760
    for(i=0;i<levelArray.length;i++){
              var skilLab:skillLabel=new skillLabel()
              skilLab.txt.text=levelArray[i]
              skilLab.name="sl"+i
              skilLab.x=30
              var graphPoint:point=new point()
              graphPoint.name="gp"+i
              graphMc.addChild(skilLab)
              graphMc.addChild(graphPoint)
    addChild(graphMc)
    // events
    function onYearsChange(e){
              yearsVal.text=yearsSb.value.toString()
              calc()
    function onDaysChange(e){
              daysVal.text=daysSb.value.toString()
              calc()
    function onMinSkilChange(e){
              skillValMin.text=levelArray[skillminSb.value-1]
        if (skillminSb.value > skillmaxSb.value) skillminSb.value = skillmaxSb.value;
        calc()
    function onMaxSkilChange(e){
              skillValMax.text=levelArray[skillmaxSb.value-1]
              if (skillmaxSb.value < skillminSb.value) skillmaxSb.value = skillminSb.value;
              calc()
    function onSubChange(e){
              subVal.text=((subSb.value)/10).toString()
              calc()
    function onCoachChange(e){
              coachVal.text=levelArray[coachSb.value-1]
              calc()
    function onAssChange(e){
              assVal.text=assSb.value.toString()
              calc()
    function onIntensityChange(e){
              intensityVal.text=intensitySb.value.toString()
              calc()
    function onStaminaChange(e){
              staminaVal.text=staminaSb.value.toString()
              calc()
    function changeEvent(e){
              calc()
    calc()
    function calc(){
              years=yearsSb.value
              days=daysSb.value
              level=skillminSb.value
              subLevel=subSb.value/10
              skillDown=skillmaxSb.value-1
              yearsFactor=Math.pow(1.0404,years+days/112-17)
              levelFactor=-1.4595*Math.pow((level+subLevel)/20,2)+3.7535*(level+subLevel)/20-0.134 9
              trainingFactor=trainingBase[trainingCb.selectedIndex]
              coachFactor=1+(7-Math.min(coachSb.value,7.5))*0.091
              assistentsFactor=1+(1.041392685-(Math.log(assSb.value+1))*Math.LOG10E)*0.2749
              intensity=1/(intensitySb.value/100)
              stamina=1/(1-staminaSb.value/100)
              weeks=yearsFactor*levelFactor*trainingFactor*coachFactor*assistentsFactor*intensity* stamina
              weeks=Math.max(weeks,1)
              skillUp=1/weeks
              baseLevel=level+subLevel
              newLevel=baseLevel
              var dosta:Boolean=false
              var weeksNo:Number=0
              var weeksCount:Number=0
              var dp:DataProvider=new DataProvider()
              while(!dosta){
                        weeksNo++
                        weeksCount++
                        days+=7
                        if(days>111){
                                  years++
                                  days=days-112
                        reCalc()
                        newLevel+=skillUp
                        if((newLevel-level)>=1){
                                  dp.addItem({ Week: weeksNo, Skill: (Math.floor(newLevel))+"-"+levelArray[Math.floor(newLevel)-1], Length:weeksCount+" weeks", Age:years+"y "+days+"d" })
                                  level++
                                  weeksCount=0
                        if((newLevel-skillDown)>=1){
                                  dp.removeItem({ Week: weeksNo, Skill: (Math.floor(newLevel))+"-"+levelArray[Math.floor(newLevel)-1], Length:weeksCount+" weeks", Age:years+"y "+days+"d" })
                                  level++
                        if(newLevel>=20 || years>=31){
                                  dosta=true
              dg.dataProvider=dp
              drawGraph(dp)
    function reCalc(){
              yearsFactor=Math.pow(1.0404,years+days/112-17)
              levelFactor=-1.4595*Math.pow(newLevel/20,2)+3.7535*newLevel/20-0.1349
              weeks=yearsFactor*levelFactor*trainingFactor*coachFactor*assistentsFactor*intensity* stamina
              weeks=Math.max(weeks,1)
              skillUp=1/weeks
    function drawGraph(dp){
              if(dp.length>0){
                        var lastRow=dp.getItemAt(dp.length-1)
                        var weekNo:Number=parseInt(lastRow.Week)
                        var topSkill:Number=parseInt(lastRow.Skill)
                        var firstRow=dp.getItemAt(0)
                        var baseSkill:Number=parseInt(firstRow.Skill)-1
                        var skillH=300/(topSkill-baseSkill)
                        var weekW=450/weekNo
                        graphMc.graphics.clear()
                        // draw greed
                        graphMc.graphics.lineStyle(2,0xffffff)
                        graphMc.graphics.moveTo(50,0)
                        graphMc.graphics.lineTo(50,300)
                        graphMc.graphics.lineTo(500,300)
                        graphMc.graphics.lineStyle(1,0xcccccc)
                        for (i=0;i<weekNo+1;i++){
                                  graphMc.graphics.moveTo(50+(450/weekNo)*i,0)
                                  graphMc.graphics.lineTo(50+(450/weekNo)*i,300)
                        for (i=baseSkill;i<=topSkill;i++){
                                  graphMc.graphics.moveTo(50,300+baseSkill*skillH-skillH*i)
                                  graphMc.graphics.lineTo(500,300+baseSkill*skillH-skillH*i)
                        // draw line
                        graphMc.graphics.lineStyle(2,0xff0000)
                        graphMc.graphics.moveTo(50,300)
                        for(i=0;i<dp.length;i++){
                                  var r=dp.getItemAt(i)
                                  var s=parseInt(r.Skill)
                                  var w=parseInt(r.Week)
                                  graphMc.graphics.lineTo(50+w*weekW,300+baseSkill*skillH-s*skillH)
                        for(i=0;i<levelArray.length;i++){
                                  var sl=graphMc.getChildByName("sl"+i)
                                  sl.y=300-skillH*(i-baseSkill+1)
                                  if(sl.y<0 || sl.y>300){
                                            sl.visible=false
                                  }else{
                                            sl.visible=true
                                  var gp=graphMc.getChildByName("gp"+i)
                                  if(i<baseSkill || i>=topSkill){
                                            gp.visible=false
                                  }else{
                                            r=dp.getItemAt(i-baseSkill)
                                            s=parseInt(r.Skill)
                                            w=parseInt(r.Week)
                                            gp.visible=true
                                            gp.txt.text=r.Age
                                            gp.txtW.text=r.Week+" w"
                                            gp.y=300-skillH*(i-baseSkill+1)
                                            gp.x=50+w*weekW
    /* Click to Go to Scene and Play
    Home.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene);
    function fl_ClickToGoToScene(event:MouseEvent):void
    removeChild(graphMc);
    //remove graphMc listeners, if there are any
    graphMc=null;
              MovieClip(this.root).gotoAndPlay(1, "Scene 1");
    stop();

    Thanks for the pointer.
    Ill try to explain better. In the calculator i want to include a checkbox that include the sliders and combobox that are wrote below.
    Also when the checkbox is selected there should be a 2nd calculation like the first one and also the output should be shown next to
    the 1st calculation. But this time the calculation should respond to the sliders and combobox that are included with the checkbox.
    // Current skill slide
    skillmin1Sb.addEventListener(Event.CHANGE,onMinSkilChange)
    // To skill slide
    skillmax1Sb.addEventListener(Event.CHANGE,onMaxSkilChange)
    for (var i=0;i<trainingArray.length;i++){
              training1Cb.addItem({label:trainingArray[i], data:trainingBase[i]})
    training1Cb.addEventListener(Event.CHANGE,changeEvent)
    training1Cb.selectedIndex=0

  • Setting cell values in DataGrid

    I have an application with a custom component called DataEntryDataGrid (which is a subclass of mx:DataGrid) that I based on this blog post:  http://blogs.adobe.com/aharui/2008/03/custom_arraycollections_adding.html
    The component works great, but in this particular datagrid I need some special functionality.   After the first row of data is entered and the user tabs into the next row, I need the first and second columns to be filled in based on the values of the previous row, and then I need it to automatically focus on the third column's cell.  While the first and second columns should be still editable, they will be largely repetitive, and it would help if the users didn't have to enter the same numbers again and again.  The first column in a new row should be the same value as the first column in the last row, and the second column in a new row should be (last row's value +1). Example:
    DataGrid:
    | Slide No. | Specimen No. | Age | Weight | Length |
    |    1      |     1        |  5  |  65    |  40    |  <- This row is manually entered, just text inputs
    |    1*     |     2*       |  #  |        |        |
    * = values set programatically, these cells should still be focusable and editable
    # = this is where the focus should be
    The problem I'm having is that when I tab into the next row, the first column value doesn't get set.  The second column gets set to the correct value and displayed correctly, and the focus is set to the correct cell (the third column), but the first column remains empty.  I'm not sure why this is.  If I set a breakpoint in the code during the function focusNewRow()  (which is called at the dataGrid's "itemFocusIn" event)  the value of "slideNo" (first column) is set to the correct value, but after the "focusNewRow" functions finishes, a trace of dataProvider[the current row].slideNo shows the value is blank.  Not null, just blank.  Traces of all other columns show the correct values.  Anyone have any ideas?  Here's the code for my main application:
    <?xml version="1.0" encoding="utf-8"?>
    <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" minWidth="955" minHeight="600" xmlns:components="components.*">
      <fx:Script>
        <![CDATA[
          import mx.controls.DataGrid;
          import mx.events.DataGridEvent;
          public function traceSlideNo():void {
            var i:int;
            var g:Object = myDataGrid.dataProvider;
            for(i = 0; i < g.length -1; i++) {
              trace("sl: " + g[i].slideNo + ", sp: " + g[i].specimenNo + ", age: " + g[i].age);
          public function focusNewRow(e:DataGridEvent):void {
            if(e.currentTarget.dataProvider.length > 0 && e.rowIndex != 0 && e.columnIndex == 0) {
              var dg:DataGrid = e.currentTarget as DataGrid;
              var lastItem:Object = dg.dataProvider[e.rowIndex - 1];
              var targetItem:Object = dg.dataProvider[e.rowIndex];
              if(targetItem.specimenNo == "") {
                var focusCell:Object = new Object();
                focusCell.rowIndex = e.rowIndex;
                focusCell.columnIndex = 2;
                dg.editedItemPosition = focusCell;
                targetItem.slideNo = int(lastItem.slideNo);
                targetItem.specimenNo = int(lastItem.specimenNo) + 1;
                callLater(dg.dataProvider.refresh);
        ]]>
      </fx:Script>
      <components:DataEntryDataGrid x="10" y="10" width="450" id="myDataGrid" itemFocusIn="focusNewRow(event)"
                      editable="true" rowHeight="25" variableRowHeight="false">
        <components:columns>
          <mx:DataGridColumn headerText="Slide No." dataField="slideNo" editable="true"/>
          <mx:DataGridColumn headerText="Specimen No." dataField="specimenNo" editable="true"/>
          <mx:DataGridColumn headerText="Age" dataField="age" editable="true"/>
          <mx:DataGridColumn headerText="Weight" dataField="weight" editable="true"/>
          <mx:DataGridColumn headerText="Length" dataField="length" editable="true"/>
        </components:columns>
      </components:DataEntryDataGrid>
      <s:Button x="10" y="195" label="Trace Slide Numbers" click="traceSlideNo()"/>
    </s:Application>
    And here's the custom component, DataEntryDataGrid, just for reference (placed in the "components" package in this example) :
    <?xml version="1.0" encoding="utf-8"?>
    <mx:DataGrid xmlns:fx="http://ns.adobe.com/mxml/2009"
           xmlns:s="library://ns.adobe.com/flex/spark"
           xmlns:mx="library://ns.adobe.com/flex/mx" initialize="init(event)"
           editable="true" wordWrap="true" variableRowHeight="true">
      <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
      </fx:Declarations>
      <fx:Script>
        <![CDATA[
          import components.NewEntryArrayCollection;
          import mx.controls.Alert;
          import mx.controls.dataGridClasses.DataGridColumn;
          import mx.events.DataGridEvent;
          import mx.events.DataGridEventReason;
          import mx.events.FlexEvent;
          import mx.utils.ObjectUtil;
          private var arr:Array = [];
          private var ac:NewEntryArrayCollection;
          private var dg:DataGrid;
          public var enableDeleteColumn:Boolean;
          private function generateObject():Object
            // Returns a new object to the datagrid with blank entries for all columns
            var obj:Object = new Object();
            for each(var item:Object in this.columns) {
              var df:String = item.dataField.toString();
              obj[df] = "";
            return obj;
          private function isObjectEmpty(obj:Object):Boolean
            // Checks to see if the current row is empty
            var hits:int = 0;
            for each(var item:Object in this.columns) {
              var df:String = item.dataField.toString();
              if(obj[df] != "" || obj[df] !== null) {
                hits++;
            if(hits > 0) {
              return false;
            return true;
          private function init(event:FlexEvent):void
            dg = this;                // Reference to the DataEntryDataGrid
            ac = new NewEntryArrayCollection(arr);  // DataProvider for this DataEntryDataGrid
            ac.factoryFunction = generateObject;
            ac.emptyTestFunction = isObjectEmpty;       
            dg.dataProvider = ac;
            // Renderer for the DELETE column and Delete Button Item Renderer
            if(enableDeleteColumn == true){
              var cols:Array = dg.columns;
              var delColumn:DataGridColumn = new DataGridColumn("del");
              delColumn.editable = false;
              delColumn.width = 35;
              delColumn.headerText = "DEL";
              delColumn.dataField = "delete";
              delColumn.itemRenderer = new ClassFactory(DeleteButton);
              cols.push(delColumn);
              dg.columns = cols;
              dg.addEventListener("deleteRow",deleteClickAccept);
          private function deleteClickAccept(event:Event):void { // Handles deletion of rows based on event dispatched from DeleteButton.mxml
            dg = this;
            ac = dg.dataProvider as NewEntryArrayCollection;
            if(dg.selectedIndex != ac.length - 1) {
              ac.removeItemAt(dg.selectedIndex);
              ac.refresh();
        ]]>
      </fx:Script>
    </mx:DataGrid>
    Also, the file NewEntryArrayCollection.as which is referenced by the custom component.  This also goes in the "components" package:
    package components
      import mx.collections.ArrayCollection;
      public class NewEntryArrayCollection extends ArrayCollection
        private var newEntry:Object;
        // callback to generate a new entry
        public var factoryFunction:Function;
        // callback to test if an entry is empty and should be deleted
        public var emptyTestFunction:Function;
        public function NewEntryArrayCollection(source:Array)
          super(source);
        override public function getItemAt(index:int, prefetch:int=0):Object
          if (index < 0 || index >= length)
            throw new RangeError("invalid index", index);
          if (index < super.length)
            return super.getItemAt(index, prefetch);
          if (!newEntry)
            newEntry = factoryFunction();
          return newEntry;
        override public function get length():int
          return super.length + 1;
        override public function itemUpdated(item:Object, property:Object = null,
                           oldValue:Object = null,
                           newValue:Object = null):void
          super.itemUpdated(item, property, oldValue, newValue);
          if (item != newEntry)
            if (emptyTestFunction != null)
              if (emptyTestFunction(item))
                removeItemAt(getItemIndex(item));
          else
            if (emptyTestFunction != null)
              if (!emptyTestFunction(item))
                newEntry = null;
                addItemAt(item, length - 1);
    Sorry for the length of this post, but I hate seeing people post without including enough information to solve the problem.  If there's anything I've left out, let me know.

    Problem solved.  Actually, the NewEntryArrayCollection pointed to an outside function within the DataEntryDataGrid component to be used as a factory function for new objects.  I just set the factory function to scan the previous row's values and base the new row's values off of them.  Thanks again, Flex!
    New private function generateObject() to replace the previous one in DataEntryDataGrid.mxml, just in case others are curious:
    private function generateObject():Object
      // Returns a new object to the datagrid with filled in slide and
      // specimen no. columns and the rest of the columns blank
      var obj:Object = new Object();
      var thisDP:Object;
      for each(var item:Object in this.columns) {
        var df:String = item.dataField.toString();
        if(df == "slideNo") {
          thisDP = this.dataProvider;
          var newSlideNo:int;
          if(thisDP.length > 1) {
         // looking for the last row of the DataGrid's dataProvider, but as
            // length is calculated differently in NewEntryArrayCollection.as
            // to account for the "dummy" row, we need to go back 2 rows.
            newSlideNo = int(thisDP[thisDP.length -2].slideNo);
          } else {
            newSlideNo = 1;
          obj[df] = newSlideNo;
        } else if(df == "specimenNo") {
          thisDP = this.dataProvider;
          var newSpecimenNo:int;
          if(thisDP.length > 1) {
            newSpecimenNo = int(thisDP[thisDP.length -2].specimenNo) + 1;
          } else {
            newSpecimenNo = 1;
          obj[df] = newSpecimenNo;
        } else {
          obj[df] = "";
      return obj;

  • Flex 3 : Need 3d Effects on Datagrid

    Hi ,
    I am using Flex 3 version fro developing my Front End .
    Is it possible to have some 3D effect on my  DataGrid .
    Seen examples on flex 4 with Datagrid , but not on Flex 3 Datagrid
    Any help ??
    Thanks .

    Paul,
    Thank you very much as it was a simple fix that I wasn’t even considering. It was typed as currency in Access and I just changed the type in Access to a number and it came through to the data grid in Flex as a number and allowed me to sort and perform additional calculations.
    Thanks again as it is much appreciated.
    -Mike

  • Dynamic datagrid rowHeight and itemRenderer problem

    Hi guys,
    Long time listener; first time caller....
    I have had a look around the forums here and i can see there are a lot of similar issues to the one i'm currently having but not so many solutions. Not sure if i'll have any better luck with my question but here goes...
    My issue is to do with the row height of a datagrid row not matching up properly with the height of the custom iterm renderer used on a column.
    The item renderer consists of an HBox containing an image and a textArea. The image will not always be present and the text area can contain a couple of words or many lines of text.
    I have overridden the measure function of the item render in which i am manually setting the HBox's height and measuredHeight.
    Problem is that i have to find some way of triggering a redraw of the datagrid AFTER if have set the item renderers height, but i dont seem to be able to directly access the in-line renderer from the parent class.
    If anyone could throw any suggestions my way it would be greatly appreciated!
    thanks '
    Dave

    Ok so here's the sample code...
    ****Renderer*****
    <?xml version="1.0" encoding="utf-8"?>
    <mx:HBox 
    horizontalAlign="
    left" verticalAlign="
    middle" horizontalGap="
    0"verticalGap="
    0"xmlns:mx="
    http://www.adobe.com/2006/mxml" horizontalScrollPolicy="
    off"verticalScrollPolicy="
    off"width="
    100%" height="
    100%"resize="measure()"
    borderColor="
    green"borderStyle="
    solid" 
    >
    <mx:Metadata>[
    Event(name="gridRowHeightChange", type="flash.events.Event")] 
    </mx:Metadata>
    <mx:Script>
    <![CDATA[
    import mx.events.ResizeEvent;
    import flash.events.Event;
    Bindable] public var showLocalPartImage:Boolean = false; 
    override public function set data(value:Object):void
         super.data = value; 
         lblPartNum.text = data.label;}
    override protected function measure():void
         super.measure(); 
         if(lblPartNum.text != "" && lblPartNum.width > 0)     {
              lblPartNum.validateNow();          lblPartNum.mx_internal::getTextField().autoSize = TextFieldAutoSize.LEFT;
              lblPartNum.height =
              this.height = measuredHeight = lblPartNum.mx_internal::getTextField().height; 
              dispatchEvent(
    new Event("gridRowHeightChange"));     }
    ]]>
    </mx:Script>
    <mx:Image id="imgLocal" horizontalAlign="center" verticalAlign="middle" visible="false" width="{0}"/> 
    <mx:TextArea id="lblPartNum" width="{this.width - imgLocal.width - 4}" height="100%" editable="false" verticalScrollPolicy="off" />
    </mx:HBox>
    ****EndRenderer*****
    ****DataGrid****
     public function measureGrid(event:Event):void{
    shoppingCart.removeEventListener(DataGridEvent.COLUMN_STRETCH, measureGrid);
    shoppingCart.invalidateList();
    shoppingCart.addEventListener(DataGridEvent.COLUMN_STRETCH, measureGrid);
     <mx:DataGrid id="shoppingCart"width="
    100%" height="100%"dataProvider="
    {_order.orderItems}"allowMultipleSelection="
    true"sortableColumns="
    true"variableRowHeight="
    true"doubleClickEnabled="
    true"doubleClick="selectPartHandler(event)"
    paddingRight="
    5"editable="
    false" 
    >
     <mx:columns>
     <mx:DataGridColumn width="22" minWidth="20" sortable="false" editable="false"/>
     <mx:DataGridColumn width="22" minWidth="20" sortable="false" editable="false"/>
     <mx:DataGridColumn minWidth="240" width="270" dataTipField="description" dataField="description" headerText="Description"editable="
    false" wordWrap="true">
     <mx:itemRenderer>
     <mx:Component>
     <controls:DescriptionShoppingCartRenderer showLocalPartImage="
    {!(outerDocument.displayUnderline)}" gridRowHeightChange="{outerDocument.measureGrid(event)}">
     </controls:DescriptionShoppingCartRenderer>  
    </mx:Component>
     </mx:itemRenderer>
     </mx:DataGridColumn>
    ****EndDataGrid****
    Unfortunately the whole code is much too large to fit in here, but here are the main working parts.
    I hope this helps.
    What i am getting when running this is strange. When i run the first time and when i resize a column, the row height is incorrect, but then when i just click the 'column stretch' arrow (ie the space between the column headers) and dont actually resize at all, the row heights re-calculate and they fit perfectly.
    This makes me think that i need to trigger this event manually AFTER the itemRenderer has been calculated.
    EDIT: forgot to add the measureGrid function

  • ItemRenderer and DataGrid Problem

    Hi guys.
    I'm on creating a small app that simply pulls information
    from an XML file, displays it in a DataGrid then allows the user to
    filter and search it. First things first though; I'll explain what
    I have so far then detail my problem.
    I get the XML file via HTTPService then place the results in
    a Bindable ArrayCollection. When the Datagrid's source is set to
    that ArrayCollection it works fine. What I am initially trying to
    do is use an itemRenderer in one of the columns that displays lines
    of text depending on the values of the current row.
    For example, the structure of my XML file is (roughly):
    <content>
    <name>Name1</name>
    <description>Description Goes Here</description>
    <audience1>yes</audience1>
    <audience2>no</audience2>
    <audience3>yes</audience3>
    </content>
    So what I am trying to do is group the audiences that each
    piece of "content" has a yes value to. So under the "Audiences"
    column in the datagrid, the above content would say
    "Audience1
    Audience3"
    as it has a yes value in between audience 1 and 3. I've tried
    writing very basic code within the itemRenderer whereby I override
    the public function set data and do some checks there but it never
    seems to work right. I've tried using Arrays within that to store
    the current audiences but I clearly haven't got the right format
    for that.
    There must be a more efficient way of doing this. I'm fairly
    new to both Flex and AS3 (been using AS2 quite a while now) but I
    have a feeling there would be some way to store each row's audience
    list in an array/object/model so I can refer to it later (I'm
    intending to filter these results by audience type later so I think
    I will HAVE to do it this way eventually). I've read quite a few
    tutorials and guides but I honestly don't know where to look
    anymore, none of them seem to cover this specific problem.
    I hope this makes sense to you guys and any guidance you
    could give me would be greatly appreciated.
    Cheers

    LabelFunction produces a display-only column.
    To filter, you will need to use the underlying data.
    Another solution to consider is to create a custom item
    class. Loop over the xmllist and build instances of the class,
    populating the properties from the xml.
    have a property who's value is calculated based on the
    audience properties values. Since it is a "real" data property in
    each item, you can filter on it directly.
    Tracy

  • Datagrid customize one column

    I have a ctyle-customized DataGrid, with embedded fonts, but
    I need one of the columns to have a smaller sized version of the
    font.
    I've used cellRenderer successfully to place an image in a
    column, but haven't found a way to drop the font size for one
    single column. Any thoughts?
    Thanks in advance,
    bh

    There are several ways, depending on what you want.
    Easiest is to use a labelFunction() instead of a dataField.
    A custom item renderer is another way.
    Yet a third way is to have your dataProvider be a collection
    of custom value objects, one of which is the calculated value.
    Tracy

  • Pagination in Advanced Datagrid ..

    I need to use pagination for Flex advanced datagrid...how should i get the length of the groupingcollection for calculating my page size....
    For the Flex datagrid i have it working as I have the length of dataprovider which will be my page size....
    Any ideas...or can anyone post an example of advanced datagrid with pagination...Will be of great help...
    Thanks

    have a look @ this http://www.adobe.com/devnet/flex/articles/flashbuilder4_datapaging_php.html

  • Calculate accurate datagrid height with variableRowHeight and without any empty row

    hi ,
    how can i calculate accurate datagrid height with variableRowHeight="true" and without getting any empty row.
    Currently i am calculating datagrid height on updateComplete event of datagrid as follows:
    public function onUpdateComplete() : void
    this.datagrid.headerHeight=50;
    datagrid.height= datagrid.measureHeightOfItems(0, this.datagrid.dataprovider.length)+this.datagrid.headerHeight;
    with following datagrid properties:
    <mx:DataGrid 
    dataProvider="{dataArrayCollection}" width="100%" rowCount="{dataArrayCollection.length}"
    id="datagrid" updateComplete="onUpdateComplete()" paddingLeft="0" paddingRight="0" paddingTop="0" paddingBottom="0"
    fontSize="12" wordWrap="true" variableRowHeight="true" verticalScrollPolicy="off" >
    With this approach the issue is, i am getting scrollbar on datagrid's container. I want scrollbar for datagrid instead of its container so that i can have only rows to be scrollable and not the header. Also, if i set verticalScrollPolicy of datagrid as "auto", i get empty rows.
    So,is there any way to have datagrid with following properties:
    variable row height
    no empty rows
    word wrap for headers as well as for rows
    Scrollbar for grid i.e. header should remain fix ,only rows should be scrollable
    no horizontal scrollbar
    TIA

    http://blogs.adobe.com/aharui/2010/10/mx-datagrid-list-and-variablerowheight
    .html

  • ADG/DataGrid prevent render even from firing immediately on property

    Hi,
    Is there any way to tell the ADG to not re-render itself immediately after a
    propertyChanged even has been fired in the dataProvider?
    I have quite a wide row (lots of cells) and lots of custom logic that updates
    these dependent properties on each row. i.e. calculated columns. I am doing the
    calculations at dataProvider level vs labelFunctions. On each "set" function of
    one of my cells in the row I raise a "propertyChanged" event if the value was
    changed. Tracing through what the ADG is doing I'm finding that its re-rendering
    each time I raise this event even if its in the same row. Is there any way to
    tell the ADG to wait a few milliseconds in case another propertyChanged event
    comes in so as to render once instead of 10 times?
    If there is no ADG option what is the best pattern for this assuming I want to
    do this in my underlying dataprovider objects. Should I raise custom events and
    fake a itemUpdated once I know there are no more changes? I don't see a clean
    way to do this however since I never really know when I'm done, and using a
    timer or something of this nature seems like a major hack.
    -Tom
    Rest of discussion from FlexCoders ...
    Re: ADG/DataGrid prevent render even from firing immediately on propertyChange
    You might try enableAutoUpdate and disableAutoUpdate on ICollectionView, not
    sure if that has the desired affect or not.
    You could also put custom events in your model objects and manually dispatch
    collection events or call explicitly tell the grid when to update.
    By "explicitly tell the grid when to update" do you mean manually calling
    itemUpdated at the View level?. If so does the grid actually "know" to re-render
    only that updated row? It seems to me that it always re-rendered all visible
    cells regardless of what was changed. So passing null or a real row into
    itemUpdated has the same results.
    Also if I am to manully dispatch propertyChanged from my row, and I never really
    know when I'm done updating all of my dependant cells is there any good way to
    do this. i.e. Cell A update cell B and cell B update updates cell E, and this
    can go on indefinatley. By catchign all property changed events at Row level and
    using a timer of say 50ms i would almost guarantee that I wouldn't rethrow more
    than a single propertyChanged event on any of the updated cells in a row. Do you
    think there is a better way to do this?
    Follow up finding,
    Do 10 propertyChanged events from my dataProvider cause grid to refresh once or
    10 times? My most recent observations show that it's just once, though for some
    reason the first load invokes my labelFunction 3 times. Is there any point in
    using enableAutoUpdate if grid appears to be 'smart' enough?

    >>And what about the the most important question, how exactly is TableAssetsViewSource defined in the XAML markup and what is
    its Source property set or bound to? And what about the reproducable sample...?
    Here is the Markup of the TableAssetsViewSource:
    <Page.Resources>
    <local:RETAILISOAMDDataSet x:Key="RETAILISOAMDDataSet"/>
    <CollectionViewSource x:Key="TableRegionsViewSource" Source="{Binding tableRegions, Source={StaticResource RETAILISOAMDDataSet}}"/>
    <CollectionViewSource x:Key="TableLocationsViewSource" Source="{Binding tableLocations, Source={StaticResource RETAILISOAMDDataSet}}"/>
    <CollectionViewSource x:Key="TableAssetsViewSource" Source="{Binding tableAssets, Source={StaticResource RETAILISOAMDDataSet}}"/>
    </Page.Resources>
    The ItemsSource of the DataGrid is bound to the TableAssetsViewSource:
    <DataGrid DataContext="{StaticResource TableAssetsViewSource}" ItemsSource="{Binding}" x:Name="TableAssetsDataGrid" AutoGenerateColumns="False" EnableRowVirtualization="True" Margin="15,10,10,10" RowDetailsVisibilityMode="VisibleWhenSelected" Grid.Column="1" HeadersVisibility="Column" CanUserResizeRows="False" IsReadOnly="True">
    Just remember, this code was auto-generated with the drag & drop onto the Page, so I did little in terms of setting the actual bindings.
    All in all, what I have done so far works as intended, except that when I want to add a row to the table it does not reflect, and that it only shows after refreshing/restarting the application.
    I will try and put together a reproducable sample.

  • Formatting a field before committing from editable datagrid

    Hi,
    I have an editable DataGrid which displays two columns, date
    and value. Now, the date in the dataProvider is actually stored as
    an integer (yyyymmdd) so I format it using a labelFunction to
    display. I then have a custom itemEditor to set it to a date for
    calling into the DateField.
    The next step, and where I'm struggling, is to update the
    dataProvider with an integer (yyyymmdd) calculated from the
    selectedDate. Can someone please help me with how to do this?
    Thanks!

    See the docs for data grid editing events, such as, I think,
    itemEndEdit.

  • OLAP Datagrid

    Hi All
    This is quite a general question but I was wondering if
    anyone was using the OLAP Datagrid in Flex 3.
    Also, I was wondering if the OLAP calculations (data) within
    the datagrid could be used to produce charts.
    Any experiences would be worth hearing.
    Best regards
    Versie

    Can any one help me convert flex3 code of olapdatagrid to flex2 but it should not give runtime error
    Thanks in advance
    Niranjan

  • Summary Row on adv. datagrid with no dataprovider

    Hello,
    Just new to Flex and still need to find out some things.
    Created two advanced datagrids, the first WITH a dataprovider returning articles .. the second datagrid was added as a sort of Shopping cart and has no dataprovider.
    I'm able to drag and drop articles from datagrid1 to datagrid2 (shopping cart), but I'm unable to show "Total price" at the bottom of the shopping cart.
    Seems logical since it need data to make summary SUM field, but how can I tackle this best?
    1. add empty dataprovider?
    2. create an datacollection on the fly?
    <mx:dataProvider>
          <mx:GroupingCollection id="gc" source="CREATE DATACOLLECTION FROM ACTUAL PRESENT DATA">
            <mx:Grouping>
               <mx:GroupingField name="Territory">
                <mx:summaries>
                  <mx:SummaryRow summaryPlacement="group">
                    <mx:fields>
                      <mx:SummaryField dataField="Price"
                        label="Total" operation="SUM"/>
                                      </mx:fields>
                  </mx:SummaryRow>
                </mx:summaries>
              </mx:GroupingField>
            </mx:Grouping>
          </mx:GroupingCollection>
        </mx:dataProvider>
    Please advice.
    thanks a million
    TomBr   

    looks like it didn't understand correctly. Solution beneath is not adding a new row, but is only a solution for adding an extra column with some calculated value.
    Am I correct that there is no default function for adding an extra row with the SUM of a column?
    ok, added a datagrid since (as you mentioned) I'll need it anyway.
    After adding a datagrid and creating a httpservice that can load data into the shopping cart, I'm still unable to add the SummaryRow with Totals
    As soon as I remove the dataprovider="{getshopcartdataArray}" parameter from "<mx:AdvancedDatagrid" and add the extra <mx:dataProviderpart (with source pointing to correct DP) ... nothing works: loading data doens't work, drag/drop doens't work anymore and total row is not seen anyware
    this is the datagrid and this is the page I used creating this: http://livedocs.adobe.com/flex/3/langref/mx/collections/SummaryRow.html
    <mx:AdvancedDataGrid y="450" id="cart" initialize="gc.refresh();" designViewDataType="flat" height="250" left="10" dragEnabled="true" dragMoveEnabled="true" dropEnabled="true" borderThickness="5" borderColor="#3F88BB" right="10">
       <mx:dataProvider>
          <mx:GroupingCollection id="gc" source="{getshopcartdataArray}">
            <mx:Grouping>
              <mx:GroupingField name="prijsexcl">
                <mx:summaries>
                  <mx:SummaryRow summaryPlacement="group">
                    <mx:fields>
                      <mx:SummaryField dataField="prijsexcl"
                        label="Total" operation="SUM"/>
                    </mx:fields>
                 </mx:SummaryRow>
               </mx:summaries>
             </mx:GroupingField>
           </mx:Grouping>
          </mx:GroupingCollection>
        </mx:dataProvider>
      <mx:columns>
            <mx:AdvancedDataGridColumn headerText="ID" dataField="cdartikel" width="30" editable="false"/>
            <mx:AdvancedDataGridColumn headerText="Zoeknaam" dataField="zoeknaam" width="40" editable="false" />
            <mx:AdvancedDataGridColumn headerText="Omschrijving" dataField="omschr" width="150" editable="false" />
            <mx:AdvancedDataGridColumn headerText="Prijs Incl" dataField="prijsincl" width="30" editable="false" />
            <mx:AdvancedDataGridColumn headerText="Prijs Excl" dataField="prijsexcl" width="30" editable="false" />
            <mx:AdvancedDataGridColumn headerText="Prijs per" dataField="prijsper" width="30" editable="false" />
            <mx:AdvancedDataGridColumn headerText="Eenheid" dataField="eenheid" width="30" editable="false" />
            <mx:AdvancedDataGridColumn headerText="Datum verschijning" dataField="verschijningsdatum" width="40" editable="false" />
            <mx:AdvancedDataGridColumn datafield="Total" />
      </mx:columns>
    </mx:AdvancedDataGrid>

Maybe you are looking for