Thursday, March 6, 2008

Percentage Width For Datagrid Columns

Specifying relative using percentage is a common need for UIs. Unfortunately I dont see a simple way to do this in Flex2.0. Penning down a workaround that works for me.
On creationComplete event of your DataGrid call a function that has a logic similar to this:

var idx:Number=0;
//myTable is the id for the dataGrid you want to manipulate
for each(var col:DataGridColumn in myTable.columns{
  switch(idx){
    case 0:
      col.width = summaryTable.width*0.23;
      break;
    case 1:
      col.width = summaryTable.width*0.13;
      break;
    case 2:
      col.width = summaryTable.width*0.10;
      break;
    case 3:
      col.width = summaryTable.width*0.11;
      break;
    case 4:
      col.width = summaryTable.width*0.11;
      break;
    case 5:
      col.width = summaryTable.width*0.11;
      break;
    case 6:
      col.width = summaryTable.width*0.17;
      break;
    case 7:
      col.width = summaryTable.width*0.04;
      break;
  }
  if(idx < summaryTable.columnCount){
    idx++;
  }
}

Yes, this is a bit ugly. Not only you need to know the exact number of columns, you need to also make sure that the sum of parts is 100. For slightly better maintainability at most you can use declared constants in the switch statement.

4 comments:

Anonymous said...

I actually just created a component called ScalableDataGrid which extends DataGrid and opens up a property called columnWidths where percentages and explicit widths can be set. Check it out on my blog. I think it is easier and more reliable to use.

Saveen said...

Interesting and good solution Nate. Thanks!

Nate said...

Thanks for linking to me Saveen. I am moving from my old free Wordpress account to http://natescodevault.com feel free to stop by!

Anonymous said...

Hi, take a look here: http://www.daveoncode.com/2009/03/18/set-datagridcolumns-width-in-percentage-with-ease/