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.