Wednesday, February 23, 2011

Working with CSV files using AS3: Part 3

Today we are going to turn each row of the data into an object and display the data in a data grid.

We will turn each row into an object, so that the main array will be an associative array, containing hashes of data, where each value is a value of a parameter (name, job, etc).

Firstly, change your for... loop this way to generate an associative array and add a line to remove the last element of the array (because it is empty):

loadedData.pop();
for (var i:int=0; i<loadedData.length; i++){
var rowArray:Array = loadedData[i].split(",");
loadedData[i] = {ID: rowArray[0], First: rowArray[1], Last: rowArray[2], Job: rowArray[3]};
}

We won' need the first line, as it is a header. We only want data in our array, so we remove the first element using the shift() method.

loadedData.shift();

Create a DataGrid component and place it on stage, give it a name of myGrid. Add this to the onload function:

import fl.data.DataProvider;
import fl.controls.dataGridClasses.DataGridColumn;

myGrid.dataProvider = new DataProvider(loadedData);

And we're going to get a data grid, which looks like this:



Full code:

var myRequest:URLRequest = new URLRequest("example.csv");
var loadedData:Array = [];
var myLoader = new URLLoader();
myLoader.addEventListener(Event.COMPLETE, onload);
myLoader.load(myRequest);

function onload(Event):void
{
loadedData = myLoader.data.split(/\r\n|\n|\r/);
loadedData.pop();
for (var i:int=0; i<loadedData.length; i++){
var rowArray:Array = loadedData[i].split(",");
loadedData[i] = {ID: rowArray[0], First: rowArray[1], Last: rowArray[2], Job: rowArray[3]};
}
loadedData.shift();

import fl.data.DataProvider;
import fl.controls.dataGridClasses.DataGridColumn;

myGrid.dataProvider = new DataProvider(loadedData);
}

Thanks for reading!

Related:

Working with CSV files using AS3: Part 1
Working with CSV files using AS3: Part 2
Working with CSV files using AS3: Part 4
Working with CSV files using AS3: Part 5

1 comment:

Fatih said...

If there is a text with a comma

Post a Comment