Sep

8

Adding a default value for a Flex ComboBox

Written by Michael Mattax

So far my experience with flex has been great, I’m still relatively new to Flex but would easily rank it in the top three web frameworks that I use. A part of this is due to Adobe’s superb documentation; In my opinion Adobe’s documentation is the best of any programming language and frameworks that I have come across.

That being said, I found myself stumped when working with a ComboBox in Flex, I wanted to create a “default” item at the first index of the ComboBox, a fairly routine practice among developers I am sure…

In the ASP.NET world one could do something like this:

DataTable dt;
...
combobox.DataSource = dt;
combobox.DataBind();
combobox.Items.Insert(0,new ListItem("- select an item -",Guid.Empty));

In Flex, controls use a dataProvider to retrieve data from any type of Bindable object; there is no way
to explicitly add a single item to a control once the dataProvider property is set. After a few minutes
of panicking and thinking of workarounds, I re-read the Flex ComboBox documentation and found the prompt property:

The prompt for the ComboBox control. A prompt is a String that is displayed in the TextInput portion of the ComboBox when selectedIndex = -1. It is usually a String like “Select one…”. If there is no prompt, the ComboBox control sets selectedIndex to 0 and displays the first item in the dataProvider.

I simply needed to set the prompt property, continuing with the example code, the equivalent Flex code is:

<mx:ComboBox id='combobox' prompt='- select an item -' />

One notable difference between the .NET and Flex methods outlined in this post, the Flex default option is not selectable and is only visible when the prompt is initially set and when the combobox’s index is programmatically set to -1.

Until next time, happy hacking.

3 Responses to “Adding a default value for a Flex ComboBox”

  1. Mark Bow Says:

    There is another way that you can add a default item to a drop down list control:

    Set the property ‘AppendDataBoundItems’ to True, add the default item and then bind your data in the code-behind.

    I enjoy reading your blogs. Keep them coming!

  2. Mark Russett Says:

    I love the simplicity… I’m still “learning” Flex and this is great to know, thanks!

  3. BradandPitti Says:

    very nice site :)

Leave a Reply