Monday, January 3, 2011

AS3 DataGrid component: Part 1

Today we will learn about the DataGrid component.

Basically, it is a table with a lot of features. Check it out:


As you can see, there are a lot of pre-built functions for this component, such as sorting, item selecting (multiple item selecting), configurable column widths, vertical and horizontal scroll bars, and more.

Let's try making one. First, put the DataGrid component on stage from your Components menu and give it an instance name of "myGrid".

Now, let's start writing our code. Firstly, we move it to our desired position and set sizes:

myGrid.move(10,10);
myGrid.setSize(300, 100)

The next thing we want to do is to create the header - the first row in the whole table. I'm creating a userbase data grid, so my columns will be called Name, Age and Job.

myGrid.columns = ["Name", "Age", "Job"];

Now we can set the width of these columns:

myGrid.columns[0].width = 100;
myGrid.columns[1].width = 50;
myGrid.columns[2].width = 150;

Then we create the array of our data. Make sure that the parameters in the array object equal the names of the columns:

var myData:Array = [{Name: "John Jenkins", Age: "31", Job: "Shop manager"},
{Name: "Anna Watson", Age: "28", Job: "Doctor"},
{Name: "Susan McCallister", Age: "29", Job: "Chef"},
{Name: "Joe Thompson", Age:"32", Job: "Janitor"},
{Name: "Bob Anderson", Age:"31", Job: "Bank assistant"}];

Finally, we apply this array to the grid's data provider:

myGrid.dataProvider = new DataProvider(myData);

Full code:

import fl.data.DataProvider;

myGrid.move(10,10);
myGrid.setSize(300, 100);
myGrid.columns = ["Name","Age","Job"];

myGrid.columns[0].width = 100;
myGrid.columns[1].width = 50;
myGrid.columns[2].width = 150;

var myData:Array = [{Name: "John Jenkins", Age: "31", Job: "Shop manager"},
{Name: "Anna Watson", Age: "28", Job: "Doctor"},
{Name: "Susan McCallister", Age: "29", Job: "Chef"},
{Name: "Joe Thompson", Age:"32", Job: "Janitor"},
{Name: "Bob Anderson", Age:"31", Job: "Bank assistant"}];

myGrid.dataProvider = new DataProvider(myData);

Thanks for reading!

Related:

AS3 DataGrid component: Part 2
AS3 DataGrid component: Part 3
AS3 DataGrid component: Part 4
AS3 DataGrid component: Part 5
AS3 DataGrid component: Part 6
AS3 DataGrid component: Part 7
AS3 DataGrid component: Part 8
AS3 DataGrid component: Part 9
AS3 DataGrid component: Part 10
AS3 DataGrid component: Part 11
AS3 DataGrid component: Part 12
AS3 DataGrid component: Part 13
AS3 DataGrid component: Part 14
AS3 DataGrid component: Part 15
AS3 DataGrid component: Part 16

1 comment:

Anonymous said...

No, Thank you for the post. I've looked at so many, trying to find an understandable method, and yours does the trick.

Post a Comment