Avg. Rating 4.0

Problem

You want to populate a DataGrid with custom data that user inputs in text fields.

Solution

Using addItem(), setItemAt() and removeItemAt() we can easily add/edit/remove data in a DataGrid!

Detailed explanation

Let's first add DataGrid to our application:

<mx:DataGrid id="myData" dataProvider="{myDataColl}">
  <mx:columns>
    <mx:DataGridColumn headerText="First Name" dataField="col1"/>
    <mx:DataGridColumn headerText="Last Name" dataField="col2"/>
    <mx:DataGridColumn headerText="City" dataField="col3"/>
  </mx:columns>
</mx:DataGrid>

As you notice, we already added dataProvider to DataGrid. Here is myDataColl declaration:

import mx.collections.ArrayCollection;
           
[Bindable]
private var myDataColl:ArrayCollection = new ArrayCollection();

We are going to add data do ArrayCollection and data will be added to DataGrid. We are going to enter data directly but you can use text fields to enable user enter data.

myDataColl.addItem({col1:"Dave", col2:"Stewart", col3:"New York"});
myDataColl.addItem({col1:"Mike", col2:"Wallace", col3:"Chicago"});
myDataColl.addItem({col1:"Jonathan", col2:"Franklin", col3:"Indiana"});

Great! To edit item, we are going to use setItemAt() property. Also, we need to pass item index of selected item in DataGrid. To enable user edit data, add onChange event to DataGrid and load data to text fields.

myDataColl.setItemAt({col1:"David", col2:"Stewart", col3:"New Jersey"}, myData.selectedIndex);

Removing item is also easy. DataGrid selected item index is required.

myDataColl.removeItemAt(myData.selectedIndex);

Removing all items:

myDataColl.removeAll();

That's it!

Happy coding!


+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes