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.