Set selectedItem on a Flex Combobox when the Combobox is not displayed

actionscript-3apache-flexflex4

I am trying to set selectedItem on a comboBox(mx). Following is the code :

callLater(function ():void {
        if (comboBox.dataProvider && comboBox.dataProvider.length > 0) {
            comboBox.selectedItem = comboBox.dataProvider.getItemAt(0);
        }
});

EDIT : I am creating Comboboxes programatically :

var comboBox:ComboBox = new ComboBox();

This works fine and sets the selectedItem to the first item from the data provider – but ONLY if the combobox is displayed on the screen and not hidden within a collapsible group.

I have a situation where I may have the combobox enclosed within a Collapsible Group (my own component) and not displayed until the collapsed group is expanded (see images below)

First Image : When the groups are collapsed and combobox is not displayed but created
collapsed_groups

Second Image : when the collapsed group is expanded to display the combobox – notice that the first element in the dataprovider is NOT selected as selectedItem

Expanded Group

following line is ALWAYS executed

 comboBox.selectedItem = comboBox.dataProvider.getItemAt(0);

But the first item is not selected in the case when the combobox is enclosed in a collapsed group – works fine when the combobox is enclosed in an expanded group.

I think this is a bug in flex – unless someone thinks otherwise ?

Best Answer

The problem is that you can not know when the object is added to the stage. As you alread mentioned, the item will not be set if the component is not visible.

Creation Complete is not called multiple times, therefore you need another way to do it. To make sure the item is set to the component after it is visible again, just call the 'callLater' method on the comboBox itself (Then the method is just called after the component has been rendered again, instead of you whole application)

var comboBox:ComboBox = new ComboBox();

comboBox.callLater(function ():void {
    if (comboBox.dataProvider && comboBox.dataProvider.length > 0) {
        comboBox.selectedItem = comboBox.dataProvider.getItemAt(0);
    }
});
Related Topic