DataGrid creation in Flex Builder 3 through Actionscript 3

I tried a few times to update a datagrid, created in MXML, with information from an XML file. Only to discover that it wasn’t easy to get away from caching issues that I was running into as a result of my itemRenderer. My solution was to build the datagrid, from scratch, in each instance and delete it when I needed to fetch a new result. Thus eliminating my caching problem, as the previous data was completely cleared. Problem was, I couldn’t find anything that told me the correct way to create a DataGrid in AS3 inside my MXML app. I pieced it together and here’s a simple example.

Disclaimer: There may be a better way to do this, but it worked, and I’m happy.

import mx.charts.series.ColumnSeries;
import mx.controls.dataGridClasses.DataGridColumn;
import mx.controls.DataGrid;

// Creating the dataprovider
var myXML:XMLList = event.result.item;

// Creating the datagrid itself
var myGrid:DataGrid = new DataGrid;
  // Setting some properties
  myGrid.dataProvider = myXML;
  myGrid.width = 320;
  myGrid.rowCount = myXML.length();
  myGrid.rowHeight = 25;

// Creating the first column
var columnOne:DataGridColumn = new DataGridColumn;
  // Setting some properties
  columnOne.headerText = 'Column One';
  columnOne.width = 25;

// Creating the second column
var columnTwo:DataGridColumn = new DataGridColumn;
  // Setting properties
  columnTwo.headerText = 'Column Two';

// New array to hold the column information
var cols:Array = new Array;
  // Add the column information to the new array

// Apply the array to the datagrid
myGrid.columns = cols;

// Add the datagrid to the workspace so it will display
mx.core.Application.application.addChild(myGrid); // In this case my datagrid was created inside a component, so I had to reference the parent when passing it.