jump to navigation

Manipulating the DataGrid component in Flash CS3 September 12, 2010

Posted by Tournas Dimitrios in Flash.
trackback

These code snippets are just a note for me . They will be a reference for future projects .I hope they will also be helpful for other Flash developers.

  • Data grid creation through AS3 :
// Import the necessary packages
import fl.controls.DataGrid;
import fl.controls.ScrollPolicy

//First drag a DataGrid component on stage so that the library ,
//gets a reference , and imediatly remove it from the stage.
//Open the Action Panel (F9)
// Now create a a new instance of DataGrid and name it "datagrid_AS"
var datagrid_AS:DataGrid = new DataGrid();

datagrid_AS.addColumn("Name");
datagrid_AS.addColumn("License");
// this is to make col. 3 a bit bigger
var col3 = datagrid_AS.addColumn("Description");
col3.minWidth = 350;
datagrid_AS.addItem({Name:"Moodle", License:"Free", Description:"Good for blended activity-oriented teaching"});
datagrid_AS.addItem({Name:"ATutor", License:"Free", Description:"Good for content-oriented teaching"});
datagrid_AS.addItem({Name:"Blackboard", License:"Commercial", Description:"Good for content and exercise-oriented teaching"});
datagrid_AS.addItem({Name:"MediaWiki", License:"GPL (free)", Description:"Good for writing-to-learn and technical mini-projects teaching"});

// Fix the size
datagrid_AS.width = 400;
// Set the height to the number of rows + 1 (for the header)
datagrid_AS.rowCount = datagrid_AS.length + 1;

// Position it at x=400 and y = 50
datagrid_AS.move(300, 70);

// Horizontal scrolling is on
datagrid_AS.horizontalScrollPolicy = ScrollPolicy.ON ;

// Then add it to the stage
addChild(datagrid_AS);
  • Using the Datagrid With external loaded XML:
import flash.display.MovieClip;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.events.MouseEvent;
	import flash.events.Event;
	import fl.controls.DataGrid;
	import fl.controls.ComboBox;
	import fl.controls.Button;

	var dg:DataGrid;
		var cb:ComboBox;
		var urlLoader:URLLoader = new URLLoader();
		var loadButton:Button;
		var bookXML:XML;
		setupGrid();
		setupComboBox();
		setupButton();

 function setupGrid():void {
	dg=new DataGrid();

	dg.addColumn("Title");
	dg.addColumn("InStock");
	dg.addColumn("Price");
	//This sets the size of the datagrid
	dg.setSize(600,100);
	//This is how many rows you want the datagrid to show
	dg.rowCount=5;
	//When we add colums they are put into an array
	//Here we set the first column "Title" width to 450
	dg.columns[0].width=450;

	//This set the x and y position of the datagrid
	dg.move(0,100);

	addChild(dg);
}

 function setupComboBox():void {
	cb = new ComboBox();
	//This adds item to the comboBox
	cb.addItem({label: "Flash" });
	cb.addItem({label: "Ajax" });
	cb.addItem({label: "Php" });
	//This sets the x and y positions
	cb.move(200,50);

	addChild(cb);
}

 function setupButton():void {
	loadButton = new Button();
	loadButton.label = "Load Books";
	loadButton.addEventListener(MouseEvent.CLICK, loadBooks);
	loadButton.x = 200;
	loadButton.y = 325;
	addChild(loadButton);
}
 function loadBooks(e:Event):void {
//Here the cb.selectedLabel returns a string so we call toLowerCase() on it
//and append .xml to it i.e. if 'Flash' is selected we load 'flash.xml'
	urlLoader.load(new URLRequest(cb.selectedLabel.toLowerCase()+".xml"));
	urlLoader.addEventListener(Event.COMPLETE, populateGrid);
}

 function populateGrid(e:Event):void {
		var booksXML:XML = new XML( e.target.data);
//How many items are in the xml file
		var booksLength:int = booksXML.book.length();

//This removes all the previously added data in the datagrid.
		dg.removeAll();
//Here we loop through the  nodes in the xml file, and add each as a row to the datagrid
		for (var i:int =0; i < booksLength; i++) {
dg.addItem({Title: booksXML.book[i].title,InStock: booksXML.book[i].instock,
					Price: booksXML.book[i].price});
		}
 }

// Create 3 XML files in the same directory as the Fla
// with the names :
//php.xml , flash.xml , ajax.xml
// example of the xml file shema
<?xml version="1.0"?>
<books>
	<book>
		Learning <span class="hiddenSpellError" pre="Learning ">ActionScript</span> 3.0: A Beginner's Guide
		<instock>yes</instock>
		<price>26.39</price>
	</book>
	<book>
		Essential <span class="hiddenSpellError" pre="Essential ">ActionScript</span> 3.0
		<instock>yes</instock>
		<price>34.64</price>
	</book>
</books>
  • Using embeded fonts with the  CS3 DataGrid component :
import fl.controls.dataGridClasses.DataGridColumn;
 import fl.controls.dataGridClasses.HeaderRenderer;
 import fl.data.DataProvider;
 var f1:Font = new CusomFont() as Font;
 var headerTF:TextFormat = new TextFormat();
 headerTF.bold = true;
 headerTF.color = 0x0000ff;
 headerTF.size = 20;
 headerTF.font = f1.fontName;
 // VerdanaheaderTF.size = 16;
 var rowTF:TextFormat = new TextFormat();
 rowTF.bold = false;
 rowTF.color = 0xff0000;
 rowTF.font = f1.fontName;
 // VerdanarowTF.size = 9;
 var fontArr:Array = Font.enumerateFonts(true);
 fontArr.sortOn("fontName", Array.CASEINSENSITIVE);
 var headRen:HeaderRenderer = new HeaderRenderer();
 headRen.setStyle("embedFonts", true);
 var fontNameCol:DataGridColumn = new DataGridColumn("fontName");
 fontNameCol.headerText = "fontName:";
 fontNameCol.headerRenderer = headRen;
 dataGrid.setRendererStyle("embedFonts", true);
 dataGrid.setRendererStyle("textFormat", rowTF);
 dataGrid.setStyle("headerTextFormat", headerTF);
 dataGrid.columns = [fontNameCol];
 dataGrid.dataProvider = new DataProvider(fontArr);
 dataGrid.rowHeight = 26;
 dataGrid.rotation = 10;
 dataGrid.rowCount = 10;
 

Further reading:

Adobe tutorials :
Other tutorials :
Official documentation for Flash and AS3 :
  • DataGrid (AS3 Language and components reference)
  • fl.data Reference manual for data associated (Adobe ActionScript 3.0 Language and Components Reference)
Advertisements

Comments»

1. Josefina Venegas - August 21, 2012

Hello, I was searching many days for an example of the combobox and datagrid like this, I just would like ask to you if there is possible use the same funcion of the combobox for a textInput, because I have an xml that I cannot make the filter to search by name, I appreciated any help you can support to me, I try to express a well as I can, I speak a little Englis, but for me is better to understand.
Thanks in addvance.
Joselyn

tournasdimitrios1 - August 21, 2012

@Joselyn
The following code is a very quick example , to get you started . For production , I would tweak the code a bit more .

 
import flash.display.MovieClip;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.events.MouseEvent;
import flash.events.Event;
import fl.controls.DataGrid;
import fl.controls.ComboBox;
import fl.controls.Button;

var urlLoader:URLLoader = new URLLoader();

setupButtons(); 
setupGrid();

txtResponse.text = "Filter books by it's value ";
//Reset txtResponse's  data
txtResponse.addEventListener(MouseEvent.CLICK , resetTxtInput) ;

function resetTxtInput(evt:MouseEvent):void {
	txtResponse.text = "" ; 
}

 function setupButtons():void {
	loadButton = new Button();
	loadButton.label = "Filter by price";
	loadButton.addEventListener(MouseEvent.CLICK, filterByPrice);
	loadButton.x = 350;
	loadButton.y = 50;
	addChild(loadButton);
	loadButton2 = new Button();
	loadButton2.label = "Load all books";
	loadButton2.addEventListener(MouseEvent.CLICK, loadAllData);
	loadButton2.x = 480;
	loadButton2.y = 50;
	addChild(loadButton2);


}

 
  function setupGrid():void {
	dg=new DataGrid();
	dg.addColumn("Title");
	dg.addColumn("InStock");
	dg.addColumn("Price");
	//This sets the size of the datagrid
	dg.setSize(600,100);
	//This is how many rows you want the datagrid to show
	dg.rowCount=5;
	//When we add colums they are put into an array
	//Here we set the first column "Title" width to 450
	dg.columns[0].width=450;

	//This set the x and y position of the datagrid
	dg.move(0,100);

	addChild(dg);
}


 function populateGrid(e:Event):void {
var myDataXML:XML = new XML( e.target.data);
//How many items are in the xml file
var dataLength:int = myDataXML.book.length();

//This removes all the previously added data in the datagrid.
dg.removeAll();
//Here we loop through the  nodes in the xml file, and add each as a row to the datagrid
for (var i:int =0; i < dataLength; i++) {
dg.addItem({Title: myDataXML.book[i].title,InStock: myDataXML.book[i].instock,
		Price: myDataXML.book[i].price});
		}
 }
 
  function populateFilteredGrid(e:Event):void {
	  trace("PopulateFilteredGrid function trigered ") ;
	  dg.removeAll();
var myDataXML:XML = new XML( e.target.data);
//How many items are in the xml file
var dataLength:int = myDataXML.book.length();
//Here we loop through the  nodes in the xml file, and add each as a row to the datagrid
for (var i:int = 0 ; i < dataLength; i++) {
	if ( myDataXML.book[i].price < txtResponse.text ) { 
dg.addItem({Title: myDataXML.book[i].title,InStock: myDataXML.book[i].instock,
		Price: myDataXML.book[i].price});
		} else {		
		continue; 
		} 
	}

 }

 function loadAllData(e:Event):void {
	trace("Function loadData trigered") ; 
	urlLoader.load(new URLRequest("data.xml"));
	urlLoader.addEventListener(Event.COMPLETE, populateGrid);
}

function  filterByPrice(e:Event):void {
	var urlLoader2:URLLoader = new URLLoader();
	urlLoader2.load(new URLRequest("data.xml"));
	urlLoader2.addEventListener(Event.COMPLETE, populateFilteredGrid);
	
}


//data.xml  file 
<?xml version="1.0"?>
<books>
	<book>
		Learning <span class="hiddenSpellError" pre="Learning ">ActionScript</span> 3.0: A Beginner's Guide
		<instock>yes</instock>
		<title> PHP</title>
		<price>26.39</price>
	</book>
	<book>
		Essential <span class="hiddenSpellError" pre="Essential ">ActionScript</span> 3.0
		<instock>yes</instock>
		<title> Actionscript</title>
		<price>34.64</price>
	</book>
	<book>
		Essential <span class="hiddenSpellError" pre="Essential ">ActionScript</span> 3.0
		<instock>yes</instock>
		<title>Ruby on Rails</title>
		<price>67.99</price>
	</book>
		<book>
		Essential <span class="hiddenSpellError" pre="Essential ">ActionScript</span> 3.0
		<instock>No </instock>
		<title>PHP  Design patterns</title>
		<price>70</price>
	</book>
			<book>
		Essential <span class="hiddenSpellError" pre="Essential ">ActionScript</span> 3.0
		<instock>Yes </instock>
		<title>PHP  Advanced programming</title>
		<price>98</price>
	</book>
</books>


Joselyn - August 22, 2012

Thanks, Thanks a lot, would you please give an idea why it throw this error?, I’m a beginner in flash as3, I will appreciated your help. I copy and paste and I have the components in the library, i have the data.xml file too.

TypeError: Error # 1009: Can not access a property or method of a null object reference.
at Sint_fla :: MainTimeline/frame1 ()

tournasdimitrios1 - August 22, 2012

@Joselyn
Your error is most probably not really in your code, but in your project setup: You seem to reference a movie clip that is not on the stage at the time you’re calling it.
Have you manually (drag-drop) on the stage the four components (2buttons , 1datagrid , 1text-inpufield) . These components should also named accordingly in the “Properties” panel (instance name) .
If your development is on Flash CS3 , I can upload you the FLA-file . Unfortunately newer versions of the Flash-IDE are not compatible .

2. Joselyn - August 22, 2012

Hi Dimitrios, I developed in Flash cs4, there any objection? 🙂

tournasdimitrios1 - August 22, 2012

@Joselyn
The concepts remain the same on all Flash IDE’s .
Just drag-drop manually all components on the stage (outside the visual area) and give each component an instance-name in the “Properties” panel (same names that where defined in the code).
Actually there are two ways to accomplish the task :

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

I made a slightly different implementation , but it works also . As I mentioned on my first respond , this was just an example , to get you started . On production applications , I would invest time to write “elegant code” .

Joselyn - August 23, 2012

Hello Dimitrius:
Thanks for your great help, it helped me to understand many thinks that I have read but I has not had implemented about components.

I am very happy with your Datagrid and Combobox example, that I was loocking for, in fact I have added to my proyect.

I just want to add a function to filter data by name, I have tried with TextInput component, but, I built it something wrong which doesn’t works, because it throw an error…

This is the code:
I will appreciated your help, and I don’t have words to say thanks
Joseyly 🙂

var itemTextInput:TextInput = new TextInput();
setupTextInput();

function setupTextInput():void {
var itemTextInput:TextInput = new TextInput();
itemTextInput.move(30, 30);
itemTextInput.width = 150
itemTextInput.addEventListener(Event.CHANGE, changeHandler);
addChild(itemTextInput);
}

function changeHandler(e:Event):void {
dg.removeAll();

var myDataXML:XML = new XML(e.target.data);
// How many items are in the xml file
var dataLength:int = myDataXML.book.length();
var a:Array = [];
// Here we loop through the nodes in the xml file and add each as a row to the datagrid
for (var i:int = 0 ; i -1)){

dg.addItem({Title: myDataXML.book[i].title,InStock: myDataXML.book[i].instock, Price: myDataXML.book[i].price});
}

1084: Error de sintaxis: se esperaba rightparen antes de colon.

tournasdimitrios1 - August 23, 2012

@Joselyn
You had a syndax error (a semicolon was missing).Check the “setupTextIput” function .

 
function setupTextInput():void {
var itemTextInput:TextInput = new TextInput();
itemTextInput.move(30, 30) ;
itemTextInput.width = 150 ; 
itemTextInput.addEventListener(Event.CHANGE, changeHandler) ;
addChild(itemTextInput) ;
}
3. Joselyn - August 25, 2012

Very Good days Dimitrios 🙂 I am very grateful for your help, but I could not finish my application I was searching and testing, I know that is very important the puntuation.
But now it doesn’t gave any error but doesn’t loads the xml either, sniff 😦 Please help me
I want my datagrid populated, then when somebody wants to search a specific name the Datagrid repopulated, could you say me, is correct my code the last I send to you?, everything else works perfectly
Thanks very much.
Regards
Joselyn

tournasdimitrios1 - August 29, 2012

@Joselyn
Download from this link a FLA file (it’s for Flash CS4) .
This is just a starting point , my intention is to show you the direction .
Homework should be done by you !!!!!!
I have used the following links as reference :

  1. The E4X approach to XML processing
  2. Adobe ActionScript 3.0 Manual
  3. Using the Datagrid Component
  4. Getting started with UI-components

ps If you need more resources let me know …….

Joselyn - August 30, 2012

Hello Dimitrios:

Thank you very much, you don’t imagine how I appreciated your help, I will try to read this links in English, I know I have to learn a lot, but people like you are a source to make the dreams can true, I will take your comment, if I need resources.

Regard
Joselyn 😀


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s