Dynamic Datagrid height without vertical scrollbar
July 22, 2008 – 1:39 amIf you ever need to have a Datagrid with no vertical scrollbars, and with a variabke height based on the content, then you may find this post interesting.
So, check this out: measureHeightOfItems () : measures a set of items from the data provider using the current item renderer and returns the sum of the heights of those items. This mean that you can find the height of the Datagrid.
If the Datagrid don't have variable row height (variableRowHeight = false), then you can multiply the rowHeight with the DataProvider length to obtain the Datagrid height. But if the Datagrid have variable row height, then you must use measureHeightOfItems () method.
I have made a easy sample with variableRowHeight.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
creationComplete="init()" viewSourceURL="srcview/index.html">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.collections.ArrayCollection;
// datagrid data provider
[Bindable]
private var dp:ArrayCollection;
// text used to populate the datagrid rows
private var txt:Array = new Array('Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas eros tellus, egestas non, suscipit vel, dignissim consectetuer, magna. Proin commodo eros et nulla.',
'Proin mattis mi id arcu. Quisque id risus ac massa consectetuer suscipit. Vestibulum eleifend. Curabitur facilisis odio. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.Nulla ut odio auctor orci facilisis feugiat. Quisque quis pede. ',
'Vivamus leo. Aenean pede risus, faucibus a, posuere eu, cursus accumsan, nisl.',
'Suspendisse sagittis lorem vel lacus. ',
'Plinius vulputate, felis in suscipit auctor, augue lorem mollis risus, eu elementum arcu velit a nisi.'
);
// init the datagrid
private function init():void
{
dp = new ArrayCollection();
addRow();
resizeDatagrid();
}
// add a new item to the datagrid data provider; this will reflect in a new row in the datagrid
private function addRow():void
{
dp.addItem({id:dp.length+1, val:txt[Math.round(Math.random()*4)]});
resizeDatagrid();
}
// resize the datagrid
private function resizeDatagrid():void
{
dg.height = dg.measureHeightOfItems(0, dp.length) + dg.headerHeight;
}
]]>
</mx:Script>
<mx:DataGrid id="dg" width="550" horizontalCenter="0" verticalScrollPolicy="off"
dataProvider="{dp}"
wordWrap="true" variableRowHeight="true" top="50">
<mx:columns>
<mx:DataGridColumn headerText="ID" dataField="id" width="50"/>
<mx:DataGridColumn headerText="Text" dataField="val"/>
</mx:columns>
</mx:DataGrid>
<mx:Button y="20" label="Add new row" click="addRow()" horizontalCenter="-226"/>
</mx:Application>
View Source is enabled.
1 Trackback(s)