views:

725

answers:

1

Hello Stackoverflowers.

Does anybody know how to add a new row to a datagrid via a checkbox.

example:

  checkbox 1 : label (PS2)
  checkbox 2 : label (PS3)
  checkbox 3 : label (PSP)

By selecting one or all of these checkboxes i what to add a new Datagrid row.

  Datagrid

  Console           price
  row1 PS2           $20,
  row2 PS3           $30,
  row3 PSP           $15,

i hope this example is clear enough thanks

DJ

+2  A: 

Add an item to the dataProvider of the DataGrid from the change event handler of the CheckBox - make sure you check for existing items (and remove them when check box is unchecked) to avoid duplicates. If you can post the code of DataGrid, we might be able to give a sample code showing how to do this.

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
    creationComplete="create()">
    <mx:DataGrid id="dg" dataProvider="{dp}">
      <mx:columns>
        <mx:DataGridColumn dataField="console"/>
        <mx:DataGridColumn dataField="price"/>
      </mx:columns>
    </mx:DataGrid>
    <mx:CheckBox id="cb1" change="onCheck(event)"/>
    <mx:CheckBox id="cb2" change="onCheck(event)"/>
    <mx:CheckBox id="cb3" change="onCheck(event)"/>
    <mx:Script>
     <![CDATA[
      import mx.collections.ArrayCollection;
      private var prices:Array = ["$20", "$30", "$15"];
      private var labels:Array = ["PS1", "PS2", "PS3"];
      private var checkBoxes:Array;
      [Bindable]public var dp:ArrayCollection;
      private function create():void
      {
       checkBoxes = [cb1, cb2, cb3];
       for(var i:Number = 0; i < labels.length; i++)
        CheckBox(checkBoxes[i]).label = labels[i];
       dp = new ArrayCollection([]);
      }
      private function onCheck(event:Event):void
      {
       var cb:CheckBox = CheckBox(event.currentTarget);
       var index:Number = indexOf(cb.label);
       if(cb.selected && index == -1)
        dp.addItem({console:cb.label, 
            price:prices[labels.indexOf(cb.label)]});
       else if(!cb.selected && index != -1)
        dp.removeItemAt(index);
      }
      private function indexOf(str:String):Number
      {
       for(var i:Number = 0; i < dp.length; i++)
       {
        var item:Object = dp.getItemAt(i);
        if(item.console == str)
         return i;
       }
       return -1;
      }
     ]]>
    </mx:Script>
</mx:Application>
Amarghosh
Thanks for your anwser.I've used your concept. I removed the prices var. Because the values of the prices column is set to editable. The prices can be set by a user. But now i'm stuck on another question?How can i catch the values of these rows and store them each in their onw var.thus meaning:Storing the column value of the ps1 price in var pricePS1Storing the column value of the ps2 price in var pricePS2Storing the column value of the ps3 price in var pricePS3ect,thanks for your helpDJ
DJ