DataGrid Tip: Row Background Color

How to change the background color of a row is an often-asked question. In Flex 2.0 it is easy. Follow these steps:

  1. Create a new class that extends mx.controls.DataGrid. This class can be an MXML file or an ActionScript file, whichever you are most comfortable with.
  2. Overide the protected function, drawRowBackground:

        override protected function drawRowBackground(s:Sprite, rowIndex:int, y:Number, height:Number,
                                                       color:uint, dataIndex:int):void
      
    {
           
    // make any tests here, then change color accordingly. For example: color = 0xFF0000;
            // call the super function to make it happen.
           
    super.drawRowBackground(s,rowIndex,y,height,color,dataIndex);
       
    }

  3. Now use your new grid in place of the <mx:DataGrid> in your application.

Within drawRowBackground you can test your data. The dataIndex argument can be used to look up the item in the dataProvider that corresponds to this row. For example, suppose you want to color any row green whose quantity is greater than 1000:

var item:Object = (dataProvider as ArrayCollection).getItemAt(dataIndex);
if( item.quantity > 1000 ) color = 0x00FF00;

It’s just that easy.