Okay, this one is for all the fellow ActionScript/Flex programmers out there.  Have you ever dumped data into a DataGrid or an AdvancedDataGrid only to have your column widths be completely off, or even your row heights be off?  Don’t you hate it when the contents of your grid’s cells are cut short?  Well here is an easy function that resizes your columns and your grid’s rowHeight so that your data is completely displayed (provided your grid is large enough, of course).

This function takes into account both width and height, and allows you to specify padding for the width and height.  It analyzes the measured display height and width of each data cell and assigns the largest values for width to each column, and the largest value for height to the DataGrid/AdvancedDataGrid’s row height.  Simply pass it the DataGrid/AdvancedDataGrid you want to optimize width and height for, and the padding values, should you want to put in padding.  I call this the xGrid Optimizicator™.  Hope it comes in useful!

import mx.controls.AdvancedDataGrid;
import mx.controls.advancedDataGridClasses.*;
import mx.controls.DataGrid;
import mx.controls.dataGridClasses.*;
 
private function optimizeDataGrid(dg:Object,widthPadding:uint = 0,heightPadding:uint = 0):void
{
if ((!dg is AdvancedDataGrid) && (!dg is DataGrid))
return;
 
var col:uint;
var tf:TextFormat;
var renderer:UITextField;
var widths:Array = new Array(dg.columnCount);
var height:uint = 0;
var dgCol:Object;
 
if (dg.columnCount > 0 && dg.dataProvider != null)
{
for (col = 0; col < dg.columnCount; ++col)
widths[col] = -1;
for each (var item:Object in dg.dataProvider)
{
for (col = 0; col < dg.columnCount; ++col)
{
if (dg is AdvancedDataGrid)
renderer = new AdvancedDataGridItemRenderer();
else
renderer = new DataGridItemRenderer();
dg.addChild(renderer);
dgCol = dg.columns[col];
renderer.text = dgCol.itemToLabel(item);
widths[col] = Math.max(renderer.measuredWidth, widths[col]);
height = Math.max(renderer.measuredHeight, height);
dg.removeChild(renderer);
}
}
for (col = 0; col < dg.columnCount; ++col)
{
// Added to take into account header text - thanks modtodd!
renderer = new DataGridItemRenderer();
dg.addChild(renderer);
renderer.text = dg.columns[col].headerText;
widths[col] = Math.max(renderer.measuredWidth,widths[col]);
dg.removeChild(renderer);
if (widths[col] != -1)
dg.columns[col].width = widths[col] + widthPadding;
}
if (height != 0)
dg.rowHeight = height + heightPadding;
}
}
Share and Enjoy:
  • Print
  • email
  • Digg
  • del.icio.us
  • Slashdot
  • Facebook
  • StumbleUpon
  • Twitter
  • Google Bookmarks