Home > Flex, code > Using ActionScript to set DataGrid columns

Using ActionScript to set DataGrid columns

July 14th, 2008

If you are setting a datagrid’s columns using mxml, it is a very simple process:

<mx:DataGrid id="myDataGrid" dataProvider="{ myData }">
    <mx:columns>
        <mx:DataGridColumn dataField="col1" headerText="Column 1" />
        <mx:DataGridColumn dataField="col2" headerText="Column 2" />
    </mx:columns>
</mx:DataGrid>

However, if you are setting the columns via ActionScript, it is also somewhat straightforward but requires a slight variation.

If I were to set the same columns on my datagrid above in ActionScript, you would perhaps first think that it would be something like this:

var myDataGridColumn:DataGridColumn = new DataGridColumn( "col1" );
myDataGridColumn.headerText = "Column 1";
myDataGrid.columns.push( myDataGridColumn );
myDataGridColumn = new DataGridColumn( "col2" );
myDataGridColumn.headerText = "Column 2";
myDataGrid.columns.push( myDataGridColumn );

This, however, does not work. The columns get overwritten and the new columns do not show up correctly.

The actual method for setting columns is to first set them to a separate array:

var columns:Array = [];
var myDataGridColumn:DataGridColumn = new DataGridColumn( "col1" );
myDataGridColumn.headerText = "Column 1";
columns.push( myDataGridColumn );
myDataGridColumn = new DataGridColumn( "col2" );
myDataGridColumn.headerText = "Column 2";
columns.push( myDataGridColumn );

Then from here, you set the dataGrid columns array to the newly created array of columns:

myDataGrid.columns = columns;

This will then force the datagrid to use the columns you have set rather than just using the properties from the dataprovider to create the column names.

This is about the 3rd time I’ve forgotten about this twist, so hopefully by writing a blog entry about it, it will solidify it for me.

Gareth Flex, code , ,

  1. Mike
    March 9th, 2009 at 18:50 | #1

    Thanks for the post.

  1. No trackbacks yet.