Remote Synthesis
Search my blog:
Viewing By Entry / Main
Jan 30, 2009

Flex 101 - Setting the Selected Items on a Flex List (or Grid)

One of the things that can be confusing when you are learning Flex is setting things like the selected items on a list or grid. I have seen a number of questions from folks on email lists and blogs on this question. Let's set the scenario. I populate a List item with all of my categories from the server and I get a blog entry from the server as well. You might think, I have a list of categories and my blog entry has an array of its categories, I can simply set my category List element's selectedItems property equal to entry.categories...this seems obvious right? Except it won't work.

Why? Well, the instances of the categories in my Array containing the full list of categories are not the same as the instances of the categories in my entry object. Its kind of like if I had two friends named Bob Smith...just because they have the same name, doesn't mean they are the same person. Instead, you need to find a way to compare the objects and see if they are the same in order to set the selected items. There is more than one way to solve this problem, but below a simple example of one of those ways. In this scenario, I am using the ID property on my object to determine if the two items are indeed the same. Its worth noting that this should also work for a DataGrid even though it was written for a List.

private function setSelectedCategories():void
{
   var a:Array = new Array();
      for each (var selectedCategory:Category in entry.categories)
      {
         for each (var category:Category in categories)
         {
            if (selectedCategory.categoryID == category.categoryID)
            {
               a.push(category);
               break;
            }
         }
      }
   categoriesList.selectedItems = a;
}

Comments

There are currently no comments for this entry.

Write your comment



(it will not be displayed)