Adobe Flex: Set Selected Item In ComboBox
Posted by tech on
October 22, 2008
Oddly, Flex does not let you set an item to be selected in its ComboBox component. While the selectedIndex property can be used, you would have to make your own method to loop through the ComboBox’s dataProvider contents to get the index. Luckily, someone saved us the trouble of creating our own component extending ComboBox. Use the code below to be used as a substitute component for mx:ComboBox.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | <?xml version="1.0" encoding="utf-8"?> <mx:ComboBox> <mx:Script> <![CDATA[ private var _selectedValue:String; private var bSelectedValueSet:Boolean = false; private var bDataProviderSet:Boolean = false; // Override committ, this may be called repeatedly override protected function commitProperties():void { // invoke ComboBox version super.commitProperties(); // If value set and have dataProvider if (bSelectedValueSet && bDataProviderSet) { // Set flag to false so code won't be called until selectedValue is set again bSelectedValueSet=false; // Loop through dataProvider for (var i:int=0; i<this.dataProvider.length; i++) { // Get this item's data var item:String = this.dataProvider[i].data; // Check if is selectedValue if(item == _selectedValue) { // Yes, set selectedIndex this.selectedIndex = i; break; } } } } // Trap dataProvider being set override public function set dataProvider(o:Object):void { // invoke ComboBox version super.dataProvider = o; // This may get called before dataProvider is set, so make sure not null and has entries if (o!=null && o.length) { // Got it, set flag bDataProviderSet = true; } } // set for selectedValue public function set selectedValue(s:String):void { // Set flag bSelectedValueSet = true; // Save value _selectedValue = s; // Invalidate to force commit invalidateProperties(); } ]]> </mx:Script> </mx:ComboBox> |
To use this custom made ComboBox, if your component file is under the folder com/ui/ then you have to specify it in the xml namespace. Setting the item in the ComboBox to be selected can be done by calling the selectedValue property (see code below).
1 2 3 4 | <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:fx="com.ui.*"> <fx:ComboBox id="cbx_1″ selectedValue="STRING_VALUE" width="150″ dataProvider="{DATA_PROVIDER_ID_HERE}"/> <mx:Application> |











December 5th, 2010 at 11:35 pm
you are welcome