When to Use labelFunction versus ItemRenderer

by Kyle Hayes on October 9th, 2007

Datagrids in Flex 2 are great because of how flexible they are in allowing you to display your data pretty much however you want, while keeping the consistent format of a grid with columns and rows.

Two of the features of the DataGridColumn objects in the DataGrid tag are ItemRenderer and labelFunction. Both allow you to change how the data is displayed to the user in the grid. Use labelFunction when you want to simply format the text (i.e. a phone number, product ID). Use an itemRenderer when you actually want to use an object of some sort in place of the label and text that is used by default (i.e. a checkbox, or button, or a custom component that you created).

Here is how you would use a labelFunction to format a phone number:




import mx.controls.dataGridClasses.DataGridColumn;
import mx.formatters.PhoneFormatter;
[Bindable]
private var arrayData:Array=[
{name:"Kyle",phone:"9995551234",phone2:"9995554321"},
{name:"Jenn",phone:"9995551111",phone2:"9995553214"}];

public function formatPhone(item:Object,col:DataGridColumn):String
{
var pf:PhoneFormatter = new PhoneFormatter();
var returnVal:String = "";
pf.formatString = "(###)###-####";
if(col.dataField == 'phone')
returnVal = pf.format(item.phone);
else if(col.dataField == 'phone2')
returnVal = pf.format(item.phone2);
return returnVal;
}
]]>








Notice that I also took into a account if I had multiple phone numbers in the object and still used a single function. You may be able to do this somewhat dynamically but I chose not to for ease of use and understanding.

Popular Posts

From Flex

4 Comments
  1. SWEET!

    I’ve been trying to do this for about 6 hours. Finally found your post and it was exactly what I needed!

    G-Man

  2. Thanks for this posting, It’s clear and instructive.
    You are the man.

  3. hello, I was wondering if you could help me!
    I have a Linechart in flex 3, and my horizontal axis is so messed up because there are too many datapoints, I need to be able to set intervals on the horizontal axis labels without compromising the resolution of the data shown in the graph!
    is it possible ?
    thanks for any help!

  4. heylo people!
    I have solved the mystery!!!
    just add a horrizontalAxisRenderers to your Chart
    and set the property canDropLabels to true!
    ActionScript Code:

    axis being the name of the axis
    you are done!!
    but if you still have questions, you can always contact me here:
    Alimsyed.com

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS