新闻频道
通过组合框(ComboBox)来过滤DataGrid
时间:2008-6-23 15:12:04 来源:银河网 作者: 编辑:

Flex中一个很普遍的应用就是用组合框(ComboBox)过滤显示在DataGrid中的数据。在这个技巧里,目的是把一个“作者” 数据库表里的数据显示到DataGrid里,表的结构如下:
CODE:
    authorId : String;
    authorName : String;
    status : String;
另外,用户可以选择ComboBox中包含的不同的作者状态的值来过滤DataGrid显示的作者信息。推荐你把从服务器请求获得的结果转换为ArrayCollection,然后把这个ArrayCollection作为DataGrid的dataProvider。这样做你会发现操作和过滤显示的数据会很变得容易。获取数据超出了现在这个技巧的范围,不过关于这个问题有很多的例子可以参考。
首先,把结果转换为ArrayCollection。
CODE:
import mx.utils.ArrayUtil;

       import mx.collections.ArrayCollection;

       // event.result contains the data from the authors search.  

       public var authorsArray : Array = mx.utils.ArrayUtil.toArray(event.result);

       // Use authorsDataProvider as the dataProvider for the dataGrid.

       [Bindable]

       public var authorsDataProvider : ArrayCollection = new ArrayCollection(authorsArray);
接下来,把搜索结果中的作者状态值动态加载到ComboBox中。在这里,数据库中可能的作家状态值是"Active", "Inactive" 和 "Deleted"。但是在进行之前,让我们来回顾一下用例。我们把搜索作者得到的结果通过DataGrid视图向用户显示出来,在看过之后,用户可能希望过滤这些数据让它只显示“Active”的作者。当然,ComboBox中的"Active", "Inactive" 和"Deleted"可以直接硬编码,但是如果那样做的话,当数据库中添加了一个新的状态值得时候我们必须修改程序。而且,ComboBox中的值应该只包含搜索结果中的作者状态,如果搜索结果只包含状态为"Active"和"Inactive"的作者,ComboBox应该只包含相应的值(没有”Delete”)。 如果所有数据库中可能的作者状态值都在ComboBox中硬编码,用户就可以选择”Delete”这个值,然后就会看到一个没有任何数据的DataGrid。我们不想困扰用户,所以接下来的代码会动态加载作者状态值到一个数组,然后把这个数组作为ComboBox的dataProvider。
CODE:
// Use the authorsStatusArray as the dataProvider for the comboBox.

     [Bindable]
     public var authorsStatusArray : Array = populateAuthorsStatusArray(authorsArray);

    public function populateAuthorsStatusArray(authorsArray:Array):Array
     {
             var statusArrayHashMap : Object = new Object();
                            var statusArray : Array = new Array;
              
             var n:int = authorsArray.length;
             for (var i:int = 0; i < n; i++)
             {
                              if (statusArrayHashMap[authorsArray [i].status] == undefined)
                              {
                                        statusArrayHashMap[authorsArray [i].status] = new Object();
                                        statusArray.push(authorsArray [i].status);
                              }
              }
             statusArray.sort();
             statusArray.unshift("All");

// The "All" value is used programmatically to un-filter (reset) the result in the dataGrid. 
return statusArray;
     }

下面是mxml写的代码:
CODE:
<mx:ComboBox id="cboAuthorsStatusFilter"
               dataProvider="{ authorsStatusArray }"
               change=" filterAuthorsGrid();"/>
这就是全部的技巧。因为DataGrid的dataProvider利用了绑定(binding),所以当用户在ComboBox中选中了一个值的时候,DataGrid会动态显示过滤后的结果。请紧记,这只是一个小技巧而且可能有一些生涩的地方。但是你应该可以通过这些代码领会这种思想。

新闻搜索

标题:

编辑推荐
暂时没有记录
相关文章