[Bindable]
public var works:Array= [
{ id: 1, name: ’feiy’, sex: ’male’},
{ id: 2, name: ’wenj’, sex: ’fmale’}];
private var worksColumns:Array= [
{ columnName: "id",headerText: "work’s id",width: 100},
{ columnName: "name",headerText: "work’s name",width: 200},
{ columnName: "sex",headerText: "work’s sex",width: 100}];
[Bindable]
public var departments:Array=[
{ id: 1, name: ’tech dept.’},
{ id: 2, name: ’service dept.’}];
private var departmentsColumns:Array= [
{ columnName: "id",headerText: "department’s id",width: 200},
{ columnName: "name",headerText: "department’s name",width:200}];
private function loadDgView(){
if(type_cb.selectedIndex==0){
view_dg.dataProvider=works;
}else{
view_dg.dataProvider=departments;
}
}
]]>
当我们选择works时,DataGrid自动根据dataProvider:works数组中的数据生成三列的DataGridColumn;而选择departments时,又相应的变更为两列,非常的方便。
DataGrid组件的这一功能是Flex1.5中所不具有的,是Flex2中的一大改进。
但是如果我们DataGrid的表头与列明不一致的时候,或者我们并不需要显示每行所有的数据,这时候DataGrid的隐式自动创建列的方法就不再适用了,这时候,我们就需要自己手动来创建列。
DataGrid使用columns属性来标识列信息,column属性是一个mx.controls.gridclasses.DataGridColumn数组,所以要动态创建表格列,只需要创建一个DataGridColumn数组,然后将其赋值给DataGrid的columns属性就可以了。前面示例的代码,我们改进如下:
import mx.controls.gridclasses.DataGridColumn;
[Bindable]
public var works:Array= [
{ id: 1, name: ’feiy’, sex: ’male’},
{ id: 2, name: ’wenj’, sex: ’fmale’}];
private var worksColumns:Array= [
{ columnName: "id",headerText: "work’s id",width: 100},
{ columnName: "name",headerText: "work’s name",width: 200},
{ columnName: "sex",headerText: "work’s sex",width: 100}];
[Bindable]
public var departments:Array=[
{ id: 1, name: ’tech dept.’},
{ id: 2, name: ’service dept.’}];
private var departmentsColumns:Array= [
{ columnName: "id",headerText: "department’s id",width: 200},
{ columnName: "name",headerText: "department’s name",width:200}];
private function loadDgView(){
if(type_cb.selectedIndex==0){
var columns:Array=new Array();
for(var i:int;i
var dgColumn:DataGridColumn=new DataGridColumn();
dgColumn.columnName=item.columnName;
dgColumn.headerText=item.headerText;
dgColumn.width=item.width;
columns.push(dgColumn);
}
view_dg.columns=columns;
view_dg.dataProvider=works;
}else{
var columns:Array=new Array();
for(var i:int;i
var dgColumn:DataGridColumn=new DataGridColumn();
dgColumn.columnName=item.columnName;
dgColumn.headerText=item.headerText;
dgColumn.width=item.width;
columns.push(dgColumn);
}
view_dg.columns=columns;
view_dg.dataProvider=departments;
}
}
]]>
红色部分为增加的代码,相对之前的代码,我们增加了两个数组:worksColumns和departmentsColumns,分别存放相应数据的DataGridColumn属性,然后在loadDgView函数中,根据相应的Column数组创建相应的DataGridColumn数组,最后将其赋值给view_db.columns。