I recently discovered a post by
FlashBulb on
Actionscript.org that helped me solve a problem I was having with assigning a value provided from a database as the default selectedItem with the Flex ComboBox. The easiest way to assign a particular item so that it will appear as the default selection in Flex is to provide the selectedIndex for that item. The trick, of course, is how do we search the ComboBox datasource in order to determine the necessary index to assign to the selectedIndex property?
Here is FlashBulb's solution, modified somewhat for Flex. If you are using an Array instead of an ArrayCollection as the datasource for your ComboBox, you can simply relace the ArrayCollection type with the Array type in the findIndex function below.
myComboBox.selectedIndex = findIndex(myArrayCollection, myItem);
//...
private function findIndex(whichArray:ArrayCollection, whichItem:String):Number
{
var ret_value:Number = 0;
for(var i:uint = 0; i < whichArray.length; i++)
{
if(whichArray[i].label == whichItem)
{
ret_value = i;
}
}
return ret_value;
};
It is important to realize that this function is searching for a specific property, "label", within the ArrayCollection. You will need to modify this to suit your needs. For instance, if your Array does not have properties you will probably need to loop by specifying the desired index (i.e. if(whichArray[1][i] ==whichItem)). This is an example of the ArrayCollection that I used:
public var myArrayCollection:ArrayCollection = new ArrayCollection([
{label:"Production", data:"0"},
{label:"Support", data:"1"},
{label:"Graphic Design", data:"2"}
]);