Add labelfunction adjustColumnWidth in Datagrid... And write a function..
private function adjustColumnWidth(item:Object,column:DataGridColumn):String
{
var columnText:String = item[column.dataField];
if(((columnText.length)*7) > column.width)
{
column.width = columnText.length * 7;
}
return columnText;
}
How about this?
ReplyDeleteprivate function optimizeColumnWidths (dg:DataGrid):void
{
var dgCol:DataGridColumn;
var renderer:UITextField;
var tf:TextFormat;
var col:int;
if (dg.columnCount > 0 && dg.dataProvider != null)
{
// initialize widths array
var widths:Array = new Array (dg.columnCount);
for (col = 0; col < widths.length; ++col)
{
widths[col] = -1;
}
// go through each data item in the grid, estimate
// the width of the text in pixels
for each (var item:Object in dg.dataProvider)
{
for (col = 0; col < widths.length; ++col)
{
// TODO: it's ok to reuse renderer, but I chose not
// to for safety reasons. Optimize if needed.
renderer = new DataGridItemRenderer();
// Must add to datagrid as child so that it inherits
// properties essential for text width estimation,
// such as font size
dg.addChild(renderer);
dgCol = dg.columns[col] as DataGridColumn;
renderer.text = dgCol.itemToLabel(item);
widths[col] = Math.max(renderer.measuredWidth + 10, widths[col]);
// remove renderer from datagrid when we're done
dg.removeChild(renderer);
}
}
// go through headers in the grid, estimate the width of
// the text in pixels, assuming the text is bold
for (col = 0; col < widths.length; ++col)
{
// TODO: it's ok to reuse renderer, but I chose not
// to for safety reasons. Optimize if needed.
renderer = new DataGridItemRenderer();
// Must add to datagrid as child so that it inherits
// properties essential for text width estimation,
// such as font size
dg.addChild(renderer);
dgCol = dg.columns[col] as DataGridColumn;
renderer.text = dgCol.headerText;
tf = renderer.getTextFormat();
tf.bold = true;
renderer.setTextFormat (tf);
widths[col] = Math.max(renderer.measuredWidth + 25, widths[col]);
// remove renderer from datagrid when we're done
dg.removeChild(renderer);
}
// set width of columns to determined values
for (col = 0; col < widths.length; ++col)
{
if (widths[col] != -1)
{
trace ("Optimized width of col " + col + " to " + widths[col]);
dg.columns[col].width = widths[col];
}
}
}
}