I have a multitude of tutorials on the Flex Datagrid and none of them show you how to use percentage widths in your Datagrid. Now at the surface this seems really easy, but the way they implemented it in Flex is very unintuitive. So, today I am going to show you how to quickly get percentage based columns in your datagrid.
This is really going to be short and simple. If you are at all familiar
with Flex you know that you can use percentage widths and heights for
components. This is simple in MXML being done by simply saying width="42%" in the properties of the component. In straight Actionscript you would be comp.percentWidth = 75. Following this line of thought you would think that if you're working
with datagrid columns you could put the same width="42%". However, this doesn't work and if you look at the documentation
for DataGridColumn you'll see that it explicitly states that the widthis in pixels. Taking a look at the code below you'll notice something a little different.
<mx:DataGrid width="100%" height="100%">
<mx:columns>
<mx:DataGridColumn headerText="Name" dataField="name" width=".25" />
<mx:DataGridColumn headerText="Age" dataField="age" width=".15" />
<mx:DataGridColumn headerText="Job" dataField="job" width=".35" />
<mx:DataGridColumn headerText="Height" dataField="height" width=".25" />
</mx:columns>
</mx:DataGrid>
You catch the change? The widths are in decimals. This is the undocumented method for setting the width to a percent of the total. You have to make sure to put a width for each column and they add up to 1, of course. That is pretty much it. You can check out a demo below.
Well, I hope you caught this before I did. This is something I have looked for many of times with no success.
thanks a lot.
Cool sample. Thanks a lot...
Really cool... thnx for sharing..
Interesting, but what if you want one column to change size dynamically and all others to stay the same when the datagrid's parent container (say a panel) changes size.
eg. | date (fixed) | initials (fixed) | description (---> dynamic) |
I have tried setting fixed widths and resizable=false to all other colums except one and setting this to resizable=true which seemed to give me what I wanted until I resized the container, at which point each of the columns seem to widen.
Great tip; saved me alot of headache. One other thing I discovered is that, if setting up the datagrid columns dynamically (via .as), you'll need to wait to specify column widths until all columns are in place, regardless of whether you are specifying in pixels or decimal ratios.
It does not work if you change the datagrid width after initialized.