Flex - Setting Combobox By Value

A problem that often comes up is the inability to set a ComboBox by value. What you need to do is to iterate over the dataProvider in order to determine the index of the match and then set the selectedIndex property to the match index. Of course, if you were ambitious, you could extend the ComboBox class, add the functionality and never worry about it again. My productive laziness hasn't been that ambitious yet, so I haven't gotten around to it yet. The solution is to use something like the following the function:

private function setCBValue(cb:ComboBox, prop:String, value:Object):void {
for(var i:int=0; i < cb.dataProvider.length; i++) {
if (cb.dataProvider[i][prop] == value) {
cb.selectedIndex=i;
break;
}
}
}

Note that since we don't know the datatype of the incoming value, the safest thing to do is to expect an Object; chances are that you aren't expecting a complex object so it should not be a problem.

I won't bother with a live example, but if you need to see it working, use the following sample app:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.controls.Alert;
        
private var _myArrayCollection:ArrayCollection;
        
private function init():void {
//Alert.show("hello");
setCBValue(myComboBox,"value","Three");
            
_myArrayCollection = new ArrayCollection()
for (var i:int=0;i<10;i++) {
_myArrayCollection.addItem(new Object());
_myArrayCollection[i].label = "option " + i.toString();
_myArrayCollection[i].value = i;
}
            
myComboBox1.dataProvider = _myArrayCollection;
            
setCBValue(myComboBox1,"value",4);            
            
}
    
private function setCBValue(cb:ComboBox, prop:String, value:Object):void {
for(var i:int=0; i < cb.dataProvider.length; i++) {
if (cb.dataProvider[i][prop] == value) {
cb.selectedIndex=i;
break;
}
}
}
        
]]>

</mx:Script>
<mx:ComboBox id="myComboBox">
<mx:dataProvider>
<mx:ArrayCollection>
<mx:Object label="One" value="One" />
<mx:Object label="Two" value="Two" />
<mx:Object label="Three" value="Three" />
<mx:Object label="Four" value="Four" />
<mx:Object label="Five" value="Five" />
<mx:Object label="Six" value="Six" />
</mx:ArrayCollection>
</mx:dataProvider>
</mx:ComboBox>

<mx:ComboBox id="myComboBox1" left="120" />
    
</mx:Application>

You can see that I've included two types of ComboBox with one using a String value and the other an int.

Related Blog Entries

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
BlogCFC was created by Raymond Camden. This blog is running version 5.9.1.001. Contact Blog Owner