Aligning the header text in a DataGrid column in Flex
The following example shows how you can set the text alignment on a Flex DataGrid control’s DataGridColumn by setting the headerStyleName and textAlign styles.
Full code after the jump.
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/09/16/aligning-the-header-text-in-a-datagrid-column-in-flex/ -->
<mx:Application name="DataGrid_headerStyleName_textAlign_test"
xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white">
<mx:Script>
<![CDATA[
import mx.events.ListEvent;
private function comboBox_change(evt:ListEvent):void {
var value:String = comboBox.selectedItem.toString();
var styleName:String = "." + dataGrid.getStyle("headerStyleName");
var cssDecl:CSSStyleDeclaration = StyleManager.getStyleDeclaration(styleName);
cssDecl.setStyle("textAlign", value);
}
]]>
</mx:Script>
<mx:XML id="dp" source="data/products.xml" />
<mx:ApplicationControlBar dock="true">
<mx:Form styleName="plain">
<mx:FormItem label="textAlign:">
<mx:ComboBox id="comboBox"
dataProvider="[left,center,right,justify]"
change="comboBox_change(event);" />
</mx:FormItem>
</mx:Form>
</mx:ApplicationControlBar>
<mx:DataGrid id="dataGrid"
dataProvider="{dp.product}"
rowCount="5"
verticalScrollPolicy="on"
width="300">
<mx:columns>
<mx:DataGridColumn id="dataGridColumn1"
dataField="@name"
headerText="This is a column with a long title:"
headerWordWrap="true"
minWidth="80" />
<mx:DataGridColumn id="dataGridColumn2"
dataField="@price"
headerText="Price:"
headerWordWrap="false"
minWidth="20" />
</mx:columns>
</mx:DataGrid>
</mx:Application>
View source is enabled in the following example.
You can also set the text alignment in an external .CSS file or <mx:Style /> block, as seen in the following example:
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/09/16/aligning-the-header-text-in-a-datagrid-column-in-flex/ -->
<mx:Application name="DataGrid_headerStyleName_textAlign_test"
xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white">
<mx:Style>
DataGrid {
headerStyleName: centerBold;
}
.centerBold {
fontWeight: bold;
textAlign: center;
}
</mx:Style>
<mx:XML id="dp" source="data/products.xml" />
<mx:DataGrid id="dataGrid"
dataProvider="{dp.product}"
rowCount="5"
verticalScrollPolicy="on"
width="300">
<mx:columns>
<mx:DataGridColumn id="dataGridColumn1"
dataField="@name"
headerText="This is a column with a long title:"
headerWordWrap="true"
minWidth="80" />
<mx:DataGridColumn id="dataGridColumn2"
dataField="@price"
headerText="Price:"
headerWordWrap="false"
minWidth="20" />
</mx:columns>
</mx:DataGrid>
</mx:Application>
Due to popular demand, here is the “same” example in a more ActionScript friendly format:
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/09/16/aligning-the-header-text-in-a-datagrid-column-in-flex/ -->
<mx:Application name="DataGrid_headerStyleName_textAlign_test"
xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white"
initialize="init();">
<mx:Script>
<![CDATA[
import flash.text.TextFormatAlign;
import mx.containers.ApplicationControlBar;
import mx.containers.Form;
import mx.containers.FormItem;
import mx.controls.ComboBox;
import mx.controls.DataGrid;
import mx.controls.dataGridClasses.DataGridColumn;
import mx.core.ScrollPolicy;
import mx.events.ListEvent;
private const XML_URL:String = "data/products.xml";
private var urlLoader:URLLoader;
private var dp:XML;
private var comboBox:ComboBox;
private var dataGrid:DataGrid;
private var dataGridColumn1:DataGridColumn;
private var dataGridColumn2:DataGridColumn;
private function init():void {
urlLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE,
urlLoader_complete);
urlLoader.load(new URLRequest(XML_URL));
var arr:Array = [];
arr.push(TextFormatAlign.LEFT);
arr.push(TextFormatAlign.CENTER);
arr.push(TextFormatAlign.RIGHT);
arr.push(TextFormatAlign.JUSTIFY);
comboBox = new ComboBox();
comboBox.dataProvider = arr;
comboBox.addEventListener(ListEvent.CHANGE,
comboBox_change);
var formItem:FormItem = new FormItem();
formItem.label = "textAlign:";
formItem.addChild(comboBox);
var form:Form = new Form();
form.styleName = "plain";
form.addChild(formItem);
var appControlBar:ApplicationControlBar;
appControlBar = new ApplicationControlBar();
appControlBar.dock = true;
appControlBar.addChild(form);
addChildAt(appControlBar, 0);
dataGridColumn1 = new DataGridColumn("@name");
dataGridColumn1.headerText = "This is a column with a long title:";
dataGridColumn1.headerWordWrap = true;
dataGridColumn1.minWidth = 80;
dataGridColumn2 = new DataGridColumn("@price");
dataGridColumn2.headerText = "Price:";
dataGridColumn2.headerWordWrap = false;
dataGridColumn2.minWidth = 20;
dataGrid = new DataGrid();
dataGrid.rowCount = 5;
dataGrid.verticalScrollPolicy = ScrollPolicy.ON;
dataGrid.width = 300;
dataGrid.columns = [dataGridColumn1, dataGridColumn2];
addChild(dataGrid);
}
private function urlLoader_complete(evt:Event):void {
dataGrid.dataProvider = XML(evt.target.data).product;
}
private function comboBox_change(evt:ListEvent):void {
var value:String = comboBox.selectedItem.toString();
var styleName:String = "." + dataGrid.getStyle("headerStyleName");
var cssDecl:CSSStyleDeclaration;
cssDecl = StyleManager.getStyleDeclaration(styleName);
cssDecl.setStyle("textAlign", value);
}
]]>
</mx:Script>
</mx:Application>
Peter deHaan
Peter deHaan currently works for Adobe on the Flex SDK QA team. While not working on Flex, Flash, and ColdFusion applications, Peter enjoys making up bios and writing in 3rd person. Peter's rarely updated blog can be found at blogs.adobe.com/pdehaan/, actionscriptexamples.com, airexamples.com, and coldfusionexamples.com.
-
Add Widgets (Content Sidebar)
This is your Content Sidebar. Edit this content that appears here in the widgets panel by adding or removing widgets in the Content Sidebar area.
15 Responses to Aligning the header text in a DataGrid column in Flex
Leave a Reply Cancel reply
-
Categories
- Accordion
- AccordionHeader
- ActionScript
- AddChild
- AdvancedDataGrid
- Alert
- alpha
- Animate
- AnimateProperties
- Application
- Application (Spark)
- ArrayCollection
- BarChart
- baseColor
- beta
- beta1
- beta2
- Bitmap
- Bitmap/BitmapData
- BitmapData
- BitmapFill
- BitmapFill (Spark)
- BitmapGraphic
- BitmapImage
- BitmapImage (Spark)
- BitmapImageResizeMode
- Border (Spark)
- BorderContainer (Spark)
- Box
- BuildInfo
- Button
- Button (Spark)
- ButtonBar
- ButtonBar (Spark)
- ByteArray
- Camera
- Charting
- CheckBox
- CheckBox (Spark)
- ClassFactory
- CollectionEvent
- Color
- ColorPicker
- ColorUtil
- ComboBox
- ComboBoxArrowSkin
- Compiler
- Component
- Component (Spark)
- Configuration
- Container
- ContextMenu
- ContextMenuEvent
- ContextMenuItem
- CSSCondition
- CSSSelector
- CSSStyleDeclaration
- CurrencyFormatter
- CursorManager
- Data Binding
- DataGrid
- DataGrid (Spark)
- DataGridColumn
- Date
- DateBase
- DateChooser
- DateField
- DateFormatter
- Debugging
- DefaultComplexItemRenderer
- DefaultTileListEffect
- DropDownList
- DropDownList (Spark)
- DropDownListButtonSkin
- DropDownListSkin
- DropShadowFilter
- E4X
- Effects
- Ellipse
- EmailValidator
- Embed
- Event
- Fade
- FileFilter
- FileReference
- fill
- Filters
- Flash
- Flash Integration
- FlashVars
- Flex 3 SDK
- Flex Builder
- Flex Builder 3
- Flex SDK
- Flex4
- FLVPlayback
- FocusManager
- FontLookup
- Fonts
- Form
- Form (Spark)
- FormHeading (Spark)
- FormItem
- FormItem (Spark)
- Forms
- FTETextField (Spark)
- FullScreen
- FullScreenEvent
- FxAnimateColor
- FxButtonBar
- FxCheckBox
- FXG
- FxHScrollBar
- FxHSlider
- FxList
- FxNumericStepper
- FxRadioButton
- FxRotate3D
- FxScroller
- FxTextArea
- FxTextInput
- FxToggleButton
- FxVScrollBar
- FxVSlider
- getStyleDeclaration()
- GradientEntry
- Graphic (Spark)
- HBox
- HDividedBox
- HGroup (Spark)
- HorizontalLayout
- HorizontalList
- HSBColor (Spark)
- HScrollBar (Spark)
- HSlider
- HSlider (Spark)
- HTML template
- ID3Info
- Image
- Image (Spark)
- ImageSnapshot
- itemRenderer
- JointStyle
- Label
- Label (Spark)
- Legend
- LegendItem
- LigatureLevel
- Line
- LinearGradientStroke
- LineScaleMode
- LinkBar
- LinkButton
- List
- List (Spark)
- Menu
- MenuBar
- Metadata
- MetadataEvent
- Model
- Mouse
- MouseCursor
- MouseEvent
- Move
- Namespace
- NavigatorContent (Spark)
- needsSWF
- NetConnection
- NetStream
- Nightly Builds
- NumberBaseRoundType
- NumberFormatter
- NumberValidator
- NumericCompare
- NumericStepper
- NumericStepper (Spark)
- ObjectProxy
- ObjectUtil
- paddingLeft
- paddingRight
- Panel
- Panel (Spark)
- Parallel
- Path
- PieChart
- PieSeries
- PieSeriesItem
- PopUpAnchor (Spark)
- PopUpButton
- PopUpManager
- ProgrammaticSkin
- ProgressBar
- PropertyChangeEvent
- QName
- RadialGradient
- RadioButton
- RadioButton (Spark)
- RadioButtonGroup
- RadioButtonGroup (Spark)
- Rect
- RegExp
- Regular Expressions
- Repeater
- RichEditableText
- RichText
- RichText (Spark)
- RichTextEditor
- Rotate
- Rotate3D (Spark)
- Scroller (Spark)
- Sequence
- setStyle()
- SimpleText
- SimpleText (Spark)
- skinClass
- Slider
- SliderEvent
- SolidColor
- SolidColorStroke
- Sort
- SortField
- Sound
- SoundEffect
- Spinner (Spark)
- SpriteVisualElement (Spark)
- StageDisplayState
- States
- StringUtil
- StringValidator
- StyleManager
- Styles
- SWFLoader
- SWFObject
- System
- SystemManager
- TabBar
- TabBar (Spark)
- TabNavigator
- TabStopFormat
- Text
- Text Layout Framework (TLF)
- TextArea
- TextArea (Spark)
- TextBox
- TextConverter
- TextEvent
- TextFlow
- TextFlowUtil
- TextFormat
- TextGraphic
- TextInput
- TextInput (Spark)
- TextLayoutFormat
- TextView
- Themes
- TileLayout
- TileList
- TileOrientation
- Timer
- TitleWindow
- TitleWindow (Spark)
- TLF
- ToggleButton (Spark)
- ToggleButtonBar
- ToolTip
- Transition
- Tree
- TruncationOptions
- UIComponent
- UIFTETextField
- Updater
- URLLoader
- URLRequest
- URLUtil
- URLVariables
- ValidationResultEvent
- Validator
- Validators
- VBox
- VDividedBox
- Vector
- VerticalLayout
- VerticalLayout (Spark)
- VGroup (Spark)
- Video
- VideoDisplay
- VideoElement
- VideoElement (Spark)
- VideoEvent
- VideoPlayer (Spark)
- VideoPlayerScrubBar
- ViewStack
- VScrollBar (Spark)
- VSlider
- VSlider (Spark)
- XML
- XMLList
- XMLListCollection
- ZipCodeValidator
- ZipCodeValidatorDomainType
- Zoom
-
Articles
- December 2010
- November 2010
- October 2010
- September 2010
- August 2010
- July 2010
- June 2010
- May 2010
- April 2010
- March 2010
- February 2010
- January 2010
- December 2009
- November 2009
- October 2009
- September 2009
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- January 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
-
Meta


It’s a great example, but is there any way to align also the header of the second column on vertical? So that “Price” label to be centered, not top.
Wonder if there is a way of setting the style per column header? All left or all right etc. is no good. The header style depends on the column data. E.g. text columns left aligned, currency columns right aligned…data and header!
Matthias,
To align an individual DataGridColumn’s header (and data), you can set the
textAlignstyle on that column:<mx:DataGrid id="dataGrid" dataProvider="{dp.product}" rowCount="5" verticalScrollPolicy="on" width="300"> <mx:columns> <mx:DataGridColumn id="dataGridColumn1" dataField="@name" headerText="This is a column with a long title:" headerWordWrap="true" textAlign="left" minWidth="80" /> <mx:DataGridColumn id="dataGridColumn2" dataField="@price" headerText="Price:" headerWordWrap="false" textAlign="right" minWidth="20" /> </mx:columns> </mx:DataGrid>Peter
Also, if you want to align/style the header separately from the column contents, you can set the
headerStyleNamestyle:<mx:Style> .centerAligned { textAlign: center; color: red; } </mx:Style> <mx:DataGrid id="dataGrid" dataProvider="{dp.product}" rowCount="5" verticalScrollPolicy="on" width="300"> <mx:columns> <mx:DataGridColumn id="dataGridColumn1" dataField="@name" headerText="This is a column with a long title:" headerWordWrap="true" textAlign="left" minWidth="80" /> <mx:DataGridColumn id="dataGridColumn2" dataField="@price" headerText="Price:" headerWordWrap="false" headerStyleName="centerAligned" textAlign="right" minWidth="20" /> </mx:columns> </mx:DataGrid>Peter
Thanks Peter.
the problem is twofold:
I’m using the AdvancedDataGrid and AdvancedDateGridColumn classes
I create the entire advanced datagrid in actionscript and the column number varies. So I can’t use any MXML. It also can be that the alignment of the header differs from the alignment of the column data.
Whereas I’m able to set the styles attributes for the column data in action script, I have difficulties doing it for the headers.
I followed your actionscript sample and I can’t even get this to work with the AdvancedDataGrid classes. Your actionscript sample above would only change the first column header and not both.
With my code the whole thing doesn’t work. Of course my use of the AdvancedDataGrid is somewhat more complex. E.g. I use different custom renderers for each column.
Could it be that there are some issues with the AdvancedDataGrid classes?
Matthias,
I haven’t used the AdvancedDataGrid classes yet, but if it isn’t working for you there may be a bug (or perhaps the syntax is just different for DataGrid and AdvancedDataGrid).
I’d suggest posting on the FlexCoders mailing list and see if anybody there has tried creating an AdvancedDataGrid in ActionScript and setting column/header alignment.
Sorry,
Peter
Thanks anyway :-)
Peter,
I would like to ask the same question as Sanda S. above: is there a way to center vertically the text of the headers.
Thanks for a great blog!
-Lev
Thanks much!
Peter I’d like to ask as Sanda did above. I cannot find a way to align my DataGrid header’s text vertically. Have you any hint please?
thanks
Any tips for aligning vertically?
Maybe someone already has an idea how to align text vertically having wordwrap enabled?
how to wrap text in datagrid column while using item renderers?
Hi Peter,
Is it possible to align vertically through CSS ??
Same question – how to align vertically… Thanks a lot.