Dynamically creating a DataGrid instance in Flash using ActionScript 3.0

by Peter deHaan on December 8, 2008

in DataGrid

When creating projects with components, you’ll often need to create a component instance dynamically instead of at authoring time. Creating a component dynamically allows your applications to be more flexible and your code to be slightly more portable because you can add, reposition and resize instances using ActionScript.

There are two main ways to create a DataGrid component instance in your Flash documents:

  • Drag a DataGrid component instance directly onto the Stage and give it an instance name.
  • Add a DataGrid component to your document’s library and create a new instance using the new operator.

Full code after the jump.

With a DataGrid component symbol already in your Flash document’s library, add the following code to the main timeline:

// ActionScript 3.0
import fl.controls.DataGrid;
 
var myDataGrid:DataGrid = new DataGrid();
myDataGrid.addColumn("columnA");
myDataGrid.addColumn("columnB");
myDataGrid.addItem({columnA:"Row 1A", columnB:"Row 1B"});
myDataGrid.addItem({columnA:"Row 2A", columnB:"Row 2B"});
myDataGrid.addItem({columnA:"Row 3A", columnB:"Row 3B"});
myDataGrid.width = 200;
myDataGrid.move(10, 10);
addChild(myDataGrid);

The previous code imports the DataGrid class, and creates a new instance of the DataGrid component. Next, it adds two data grid columns, columnA and columnB, and adds three items to the data grid’s data provider using the addItem() method. Finally, the data grid is resized, repositioned and added to the display list.

For more information on the Flash/ActionScript 3.0 DataGrid component, see the “Creating, populating, and resizing the DataGrid component” Flash Quick Start on Adobe.com.

{ 0 comments… add one now }

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Previous post:

Next post: