Macromedia Flex Macromedia Flex
Set the selected item for a comboBox or dataGrid

Jun 15, 2005 - Set the selected item for a comboBox or dataGrid
Loop over the dataProvider items, find a match for a value, and set the current selected line

BSince the Flex 1.5 list-based controls do not support a "selectedItem" method, if you want to programatically set the control to a given value, you must loop over the items in the dataGrid, find a match, then set the selectedIndex.

The sample below does that for a comboBox and a dataGrid, plus shows setting vPosition to scroll the selection into view on the dataGrid.  It also has a simple labelFunction to build a label for the combo box.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="" horizontalAlign="left"
 private var gaDP1:Array;
 private function initApp():Void
  gaDP1 = [ {label:"A", data:0},
     {label:"B", data:1},
     {label:"C", data:2},
     {label:"D", data:3},
     {label:"E", data:4},
     {label:"F", data:5},
     {label:"G", data:6},
     {label:"H", data:7},
     {label:"I", data:8},
     {label:"J", data:9}];  //build the dataProvider
 //runs on click of button
 private function setInitialItem():Boolean
  var aDP:Array = mx.utils.ArrayUtil.toArray(cbo1.dataProvider);
  var sDataValueInit:String = tiInitialData.text;
  var sDataValueCur:String;
  for ( var i:Number=0; i<aDP.length; i++ )  {  //loop over the items in the dataProvider
   sDataValueCur = aDP[i].data;  //get the current value
   if ( sDataValueCur == sDataValueInit )  {  //compare desired value to current value
    cbo1.selectedIndex = i;  //set the seletedIndex of the combo box
    dg1.selectedIndex = i;  //set the seletedIndex of the dataGrid
    dg1.vPosition = dg1.selectedIndex;  //scroll the dtagrid so the selected item is visible
    return true;
  }//for ( var i:Number=0;....
  return false;
 //example of labelFunction.  Creates a label out of both properties
 private function lfCB1(oItem:Object):String
  return oItem.label + "  ( data:" + + ")";
  <mx:Label text="Initial Data Value (0-9)" />
  <mx:TextInput id="tiInitialData" />
  <mx:Button label="Set Item" click="setInitialItem()"/>

    <mx:ComboBox id="cbo1" dataProvider="{gaDP1}" width="150" labelFunction="lfCB1" />
  <mx:DataGrid id="dg1"  dataProvider="{gaDP1}" rowCount="4">
           <mx:DataGridColumn headerText="Label" columnName="label" />
           <mx:DataGridColumn headerText="Data" columnName="data" />

File Details
Created On Jun, 15, 2005 by Tracy Spratt
Last Modified On Jun, 15, 2005 by Tracy Spratt
Group: Tips and Articles
Flex Versions: All
Category: Controls:Input (eg Buttons/Choosers/Sliders)
Type: Complete Lesson
Difficulty: Beginner
Keywords: selectedIndex selectedItem