Search Flex Components Free

Custom Search

July 6, 2009

Flex Associative Arrays

In this example I will be showing the use of associative array to change the content of a DataGrid control. Associative arrays work just like regular arrays except they use an Object (normally a string) as their index. For example, inventory['price'] = 12.99. I will be creating an associative array of ArrayCollections. Each of these ArrayCollections will be used to populate a DataGrid.

First let's create the ComboBox and the DataGrid controls:

dataProvider="{categories}"
change="changeCBHandler()">


dataProvider="{searchList}">







Now let's look at the code used in these examples. Comments are provided throughout the code.


import mx.collections.ArrayCollection;

//Array for the ComboBox control
[Bindable]
private var categories:ArrayCollection =
new ArrayCollection(["Search", "News"]);

//Array collections to be placed in the Associative Array
[Bindable]
private var searchList:ArrayCollection = new ArrayCollection([
{name:'Yahoo',url:'http://yahoo.com'},
{name:'Google',url:'http://google.com'},
{name:'Ask', url:'http://ask.com'}]);

[Bindable]
private var newsList:ArrayCollection = new ArrayCollection([
{name:'CNN', url:'http://cnn.com'},
{name:'Yahoo News', url:'http://news.yahoo.com'},
{name:'CNet', url:'http://cnet.com'}]);



//Associative Array
[Bindable]
private var allLists:Array = new Array();

//Intialization of the Associative array
//to be called on applicationComplete event
private function loadAllLists():void {

allLists['Search'] = searchList;
allLists['News'] = newsList;
}

//Event handler for the change event
private function changeCBHandler():void {
var category:String = cbCategory.selectedLabel;
dgSites.dataProvider = allLists[category];

}
]]>
Here is the complete application. Right click to see the complete source code.


Related Flex Tutorials