The Spark DataGrid control displays a row of column headings above a scrollable grid. The grid consists of a collection of individual cells arranged in rows and columns. The DataGrid control is designed to support smooth scrolling through a large number of rows and columns.
The Spark DataGrid control is implemented as a skinnable wrapper around the Spark Grid control. The Grid control defines the columns of the data grid, and much of the functionality of the DataGrid control itself.
The DataGrid skin is responsible for laying out the grid, the column headers, and the scroller. The skin also configures the graphic elements used to render visual elements used as indicators, separators, and backgrounds. The DataGrid skin defines a default item renderer used to display the contents of each cell.
The Spark DataGrid control provides the following features:
Interactive column width resizing
Control of column visibility
Cell and row selection
Single item and multiple item selection modes
Customizable column headers
Cell editing
Column sorting
Custom item renderers and item editors
Custom skins to control all aspects of the appearance of the DataGrid control
You use the <s:DataGrid> tag to define a Spark DataGrid control in MXML. Specify an id value if you intend to refer to a component elsewhere in your MXML, either in another tag or in an ActionScript block.
The DataGrid control uses a list-based data provider to supply the data to display. The data provider consists of a list of objects called items. Each item corresponds to one row of the DataGrid control. Each grid column typically corresponds to one property of each row item. For more information, see Data providers and collections.
<?xml version="1.0" encoding="utf-8"?>
<!-- dpcontrols\sparkdpcontrols\SparkDGSimple.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:DataGrid>
<s:dataProvider>
<s:ArrayList>
<fx:Object>
<fx:Artist>Pavement</fx:Artist>
<fx:Price>11.99</fx:Price>
<fx:Album>Slanted and Enchanted</fx:Album>
</fx:Object>
<fx:Object>
<fx:Price>11.99</fx:Price>
<fx:Artist>Pavement</fx:Artist>
<fx:Album>Brighten the Corners</fx:Album>
</fx:Object>
</s:ArrayList>
</s:dataProvider>
</s:DataGrid>
</s:Application>
By default, each column displays one property from each data provider item. Each column heading displays the name of the associated property in the data provider item.
The index of rows in the DataGrid control is zero-based, meaning values are 0, 1, 2, ... , n ‑ 1, where n is the total number of items in the data provider. Column indexes are also zero-based. Therefore, if you select the first cell in the second row, the row index is 1 and the column index is 0.
Specify the data provider for the DataGrid control by using the dataProvider property. The data type of the dataProvider property is IList. That lets you use an ArrayList, ArrayCollection, or any other class that implements IList as the data provider.
ArrayList is a lightweight implementation of IList that is useful if you do not support row sorting in the DataGrid control. To support row sorting, use a class that implements the ICollectionView interface, such as ListCollectionView. Typically, you use a subclass of ListCollectionView, such as ArrayCollection or XMLListCollection, as the data provider to support row sorting.
Each row in the data grid corresponds to one item in the data provider. Data provider items can define their properties in differing orders. By default, the order of the columns corresponds to the order of the properties as defined in the first item in the data provider.
If a data provider item omits a property or a value for a property, the DataGrid control displays an empty cell in the corresponding column for that row.
<?xml version="1.0" encoding="utf-8"?>
<!-- dpcontrols\sparkdpcontrols\SparkDGPassedData.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
initialize="initData();">
<fx:Script>
<![CDATA[
import mx.collections.*;
private var dgArray:Array = [
{Artist:'Pavement', Album:'Slanted and Enchanted', Price:11.99},
{Artist:'Pavement', Album:'Brighten the Corners', Price:11.99}];
[Bindable]
public var initDG:ArrayCollection;
// Initialize initDG variable from the Array.
public function initData():void {
initDG = new ArrayCollection(dgArray);
}
]]>
</fx:Script>
<s:DataGrid id="myGrid"
width="350" height="200"
dataProvider="{initDG}"/>
</s:Application>
In this example, you bind the variable initDG to the <s:dataProvider> property.
The following example populates the DataGrid control from XML data. In this example, you define the XML data by using the XMLList class. You then create an XMLListCollection object from the XMLList:
<?xml version="1.0" encoding="utf-8"?>
<!-- dpcontrols\sparkdpcontrols\SparkDGXMLData.mxml -->
<s:Application
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
width="500">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Declarations>
<fx:XMLList id="employees">
<employee>
<name>Joanne Wall</name>
<phone>555-219-2012</phone>
<email>jwall@fictitious.com</email>
<active>true</active>
</employee>
<employee>
<name>Mary Jones</name>
<phone>555-219-2000</phone>
<email>mjones@fictitious.com</email>
<active>true</active>
</employee>
<employee>
<name>Maurice Smith</name>
<phone>555-219-2012</phone>
<email>maurice@fictitious.com</email>
<active>false</active>
</employee>
<employee>
<name>Dave Davis</name>
<phone>555-219-2000</phone>
<email>ddavis@fictitious.com</email>
<active>true</active>
</employee>
<employee>
<name>Tom Maple</name>
<phone>555-219-2000</phone>
<email>tmaple@fictitious.com</email>
<active>true</active>
</employee>
</fx:XMLList>
<s:XMLListCollection id="employees2" source="{employees}"/>
</fx:Declarations>
<s:DataGrid id="dg" width="500" dataProvider="{employees2}">
<s:columns>
<s:ArrayList>
<s:GridColumn dataField="name" headerText="Name"/>
<s:GridColumn dataField="phone" headerText="Phone"/>
<s:GridColumn dataField="email" headerText="Email"/>
</s:ArrayList>
</s:columns>
</s:DataGrid>
<s:Form>
<s:FormItem label="Name">
<s:Label text="{dg.selectedItem.name}"/>
</s:FormItem>
<s:FormItem label="Email">
<s:Label text="{dg.selectedItem.email}"/>
</s:FormItem>
<s:FormItem label="Phone">
<s:Label text="{dg.selectedItem.phone}"/>
</s:FormItem>
</s:Form>
</s:Application>
You can use Flex data access components: HTTPService, WebService, and RemoteObject, to supply data to the DataGrid. To use a remote data source to provide data, you represent the result of the remote service with the appropriate object, as follows:
A RemoteObject component automatically returns an ArrayCollection for any data that is represented on the server as a java.util.List object, and you can use the returned object directly.
For HTTPService and WebService results, cast the result data to a collection class if the data changes or if you use the same result in multiple places (the latter case is more efficient). As a rule, use an ArrayCollection for serialized (list-based) objects and an XMLListCollection for XML data.
The following code snippet shows this use, casting a list returned by a web service to an ArrayCollection:
<s:WebService id="employeeWS" wsdl="http://server.com/service.wsdl"
showBusyCursor="true"
fault="alert(event.fault.faultstring)">
<s:operation name="getList">
<mx:request>
<deptId>{dept.selectedItem.data}</deptId>
</mx:request>
</s:operation>
...
</s:WebService>
<fx:ArrayCollection id="ac"
source="mx.utils.ArrayUtil.toArray(employeeWS.getList.lastResult)"/>
<s:DataGrid dataProvider="{ac}" width="100%">
A GridColumn object represents each column in a DataGrid control. By default, the DataGrid control creates a column for every property in the first item of the data provider.
Use the DataGrid.columns property to explicitly define the columns of the DataGrid. By explicitly defining the columns, you can set the column order, set column visibility, and set additional column properties.
The data type of the columns property is IList. That lets you use an ArrayList, ArrayCollection, or any other class that implements IList as the data provider. Most of the applications in this document use ArrayList to set the columns property.
To support column sorting, use a class that implements the ICollectionView interface, such as ListCollectionView. Typically, you use a subclass of ListCollectionView, such as ArrayCollection, as the data provider.
Use the GridColumn.dataField property to specify the property of the data provider items displayed in a column, as the following example shows:
<?xml version="1.0" encoding="utf-8"?>
<!-- dpcontrols\sparkdpcontrols\SparkDGSpecifyColumns.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:DataGrid>
<s:dataProvider>
<s:ArrayCollection>
<fx:Object Artist="Pavement" Price="11.99"
Album="Slanted and Enchanted"/>
<fx:Object Artist="Pavement"
Album="Brighten the Corners" Price="11.99"/>
</s:ArrayCollection>
</s:dataProvider>
<s:columns>
<s:ArrayList>
<s:GridColumn dataField="Album"/>
<s:GridColumn dataField="Price"/>
</s:ArrayList>
</s:columns>
</s:DataGrid>
</s:Application>
When you use the <s:columns> tag, the DataGrid only displays the columns corresponding to the specified GridColumn objects. In this example, you only define columns for the Album and Price properties of the data provider. Therefore, the DataGrid does not display a column for the Price property.
You can reorder the columns by changing the order of the GridColumn objects, as the following example shows:
<s:columns> <s:ArrayList> <s:GridColumn dataField="Price"/> <s:GridColumn dataField="Album"/> </s:ArrayList> </s:columns>
In this example, you specify that the Price column is the first column in the DataGrid control, and that the Album column is the second.
You can also use the <s:GridColumn> tag to set other options. The following example uses the headerText property to set the name of the column to a value different from the default name of Album, and uses the width property to set an explicit column width:
<s:columns> <s:ArrayList> <s:GridColumn dataField="Album" width="200"/> <s:GridColumn dataField="Price" headerText="List Price"/> </s:ArrayList> </s:columns>
<?xml version="1.0" encoding="utf-8"?>
<!-- dpcontrols\sparkdpcontrols\SparkDGTypicalItem.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark">
<s:DataGrid requestedRowCount="5">
<s:typicalItem>
<s:DataItem key="9999999" name="Typical name length"
price="1234.56" call="false"/>
</s:typicalItem>
<s:ArrayCollection id="items">
<s:DataItem key="1000" name="Abrasive" price="100.11" call="false"/>
<s:DataItem key="1001" name="Brush" price="110.01" call="true"/>
<s:DataItem key="1002" name="Clamp" price="120.02" call="false"/>
<s:DataItem key="1003" name="Drill" price="130.03" call="true"/>
<s:DataItem key="1004" name="Epoxy" price="140.04" call="false"/>
<s:DataItem key="1005" name="File" price="150.05" call="true"/>
</s:ArrayCollection>
</s:DataGrid>
</s:Application>
By default, the DataGrid control displays rows in the order specified in the data items passed to its dataProvider property. The control lets you sort data based on the cell value of a single column. To sort ascending order of a column, select the column header. Select it again to sort in descending order.
To disable sorting for the control, set the DataGrid.sortableColumns property to false. To disable sorting for an individual column, set the GridColumn.sortable property to false.
Create a custom sort by implementing a sort compare function. You can define a different sort compare function for each column of the control. For more information, see Create a custom sort for the Spark DataGrid control.
<?xml version="1.0" encoding="utf-8"?>
<!-- dpcontrols\sparkdpcontrols\SparkDGVisibleColumn.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<s:DataGrid id="myDG" width="350">
<s:ArrayCollection>
<fx:Object Artist="Pavement" Price="11.99"
Album="Slanted and Enchanted"/>
<fx:Object Artist="Pavement"
Album="Brighten the Corners" Price="11.99"/>
</s:ArrayCollection>
<s:columns>
<s:ArrayList>
<s:GridColumn dataField="Artist"/>
<s:GridColumn dataField="Album"/>
<s:GridColumn id="price" dataField="Price" visible="false"/>
</s:ArrayList>
</s:columns>
</s:DataGrid>
<!-- The column id property specifies the column to show.-->
<s:Button label="Toggle Price Column"
click="price.visible = !price.visible;" />
</s:Application>
The Spark DataGrid control is a skinnable component that uses a Grid control as a skin part. The Grid control displays a list of data items in a two-dimensional grid of cells. Each object in the data provider of the Grid control defines a single row. Individual properties of each object define each cell of the row.
A GridColumn object represents each column of the Grid control. The GridColumn object is responsible for displaying a cell value for each row of the grid. To display a cell, the GridColumn object specifies an item renderer. To edit a cell, the GridColumn object specifies an item editor.
The Grid control only creates as many item renderers as are required to display the currently visible cells. For example, you define a Grid control with hundreds or thousands of rows. Flex only creates enough item renderers to display the currently visible cells, but not for the cells that are currently off the screen.
When a cell is moved off the visible area of the screen, its item renderer is recycled. That means the item renderer can be reused when a new cell moves onto the visible area of the screen. Recycling item renderers greatly reduces the overhead required to use the Grid control.
The following list describes some other differences between the DataGrid and Grid controls:
Unlike the DataGrid control, the Grid control is not skinnable.
By default, the Grid control does not display scroll bars. To add scroll bars, wrap the Grid control in the Scroller component.
The Grid control does not provide default mouse or keyboard event handling. You must add support for those events yourself.
The DataGrid control defines event types that let you respond to user interaction. Many of these events are similar to events used by other Spark controls. For example, the DataGrid control dispatches a gridClick event when a user clicks any cell in the DataGrid control, similar to the click event used by other controls. Similarly, use the gridMouseDown and gridMouseUp events with the DataGrid control instead of the mouseDown and mouseUp events.
The DataGrid uses its own event types because it lets the DataGrid pass additional information to event handlers in the event object. For example, the DataGrid passes a spark.events.GridEvent object to the event handler of a gridClick event. The GridEvent class includes the cell location, and other information necessary to handle the event.
In your event handler, you often access properties of the DataGrid control. For example, you can access the DataGrid control by using the event.currentTarget property, where event is the event object passed to the event handler.
However, most of the properties of the DataGrid control are just references to properties of the underlying Grid control. Therefore, it is more efficient to access the Grid control directly in your event handler. You can access the Grid control by using the grid skin part of the DataGrid control, as shown below:
event.currentTarget.grid
The grid property in many event objects, such as event objects of type spark.events.GridEvent, also contains a reference to the underlying Grid control. Therefore, in an event handler where the event object contains a reference to the Grid control, you can reference it as follows:
event.grid
<?xml version="1.0" encoding="utf-8"?>
<!-- dpcontrols\sparkdpcontrols\SparkDGEvents.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
minWidth="450" minHeight="450">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
import spark.events.GridEvent;
private function gridClickEvent(event:GridEvent):void {
// Access the colunm index, row index, and event type
// by using the GridEvent object.
clickColumn.text = String(event.columnIndex);
clickRow.text = String(event.rowIndex);
eventType.text = event.type;
// Access the selection mode of the Grid control.
selectionType.text = String(event.grid.selectionMode);
}
]]>
</fx:Script>
<s:DataGrid id="myGrid" width="350" height="150"
selectionMode="multipleCells"
gridClick="gridClickEvent(event);">
<s:ArrayCollection>
<fx:Object Artist="Pavement" Price="11.99"
Album="Slanted and Enchanted" />
<fx:Object Artist="Pavement" Album="Brighten the Corners"
Price="11.99" />
</s:ArrayCollection>
</s:DataGrid>
<s:Form>
<s:FormItem label="Column Index:">
<s:Label id="clickColumn"/>
</s:FormItem>
<s:FormItem label="Row Index:">
<s:Label id="clickRow"/>
</s:FormItem>
<s:FormItem label="Selection type:">
<s:Label id="selectionType"/>
</s:FormItem>
<s:FormItem label="Type:">
<s:Label id="eventType"/>
</s:FormItem>
</s:Form>
</s:Application>
In this example, you use the event handler to display the column index, row index, event type, and selection mode.
The DataGrid control lets you configure how the user can select cells and rows. For example, you can configure the control so that selection is disabled, or so that the user can select multiple cells of the grid, or multiple rows.
The following properties of the DataGrid control determine selection:
selectionMode Specifies the selection mode of the control. Possible values are: none (selection disabled), singleCell, singleRow (default), multipleCells, and multipleRows.
requireSelection Specifies that a cell or row must always be selected. The default value is false. If true, and the selectionMode property is not none, then the first cell or row is selected by default until the user makes a selection, or until you set the selection programmatically.
Use the keyboard or mouse to interact with the DataGrid control and to change selection. For example, when using the keyboard, use the Arrow keys to change the selected item. If you configure the DataGrid control for multiple selection, select multiple items by using the Shift and Arrow keys. For more information on keyboard navigation, see Spark DataGrid control keyboard shortcuts.
The DataGrid control dispatches the selectionChanging event. In the event handler for the selectionChanging event, you can call the preventDefault() method to cancel the proposed selection change.
If the selectionChanging event is not canceled, the control dispatches a selectionChange event to indicate that the selection change has been committed.
If the selection change is committed, or if there was a change to the caret with no change to the selected item, dispatch a caretChange event.
You can change the selection programmatically by using methods of the DataGrid control. The control dispatches a valueCommit event on the change. Programmatic changes of selection are unconditionally committed, meaning that you cannot cancel them by calling the preventDefault() method.
Several properties of the DataGrid and Grid control handle cell and row selection in the control. These properties include the following:
selectedCell If the selectionMode property is singleCell, this property contains the position of the cell in the grid as represented by the CellPosition class. The CellPosition.columnIndex and CellPosition.rowIndex properties contain the cell location.
selectedIndex If the selectionMode property is singleRow, this property contains the index of the currently selected row.
selectedItem The object from the data provider corresponding to the currently selected data item. This object represents the entire row of the grid.
In the following example, when you select a row in the control, the event handler for the selectionChange event displays the row index and the lastName field of the data item in TextArea controls:
<?xml version="1.0" encoding="utf-8"?>
<!-- dpcontrols\sparkdpcontrols\SparkDGSelection.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
height="450" width="450">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
import spark.components.Grid;
import spark.events.GridSelectionEvent;
protected function selectionChangeHandler(event:GridSelectionEvent):void {
const eventGrid:Grid = event.currentTarget.grid;
var currentIndx:int = eventGrid.selectedIndex;
var currentDataItem:Object = eventGrid.selectedItem;
selIndex.text = String(currentIndx);
selLName.text = String(currentDataItem.lastName);
}
]]>
</fx:Script>
<s:DataGrid id="myDG" width="100%"
selectionChange="selectionChangeHandler(event)">
<s:ArrayCollection>
<fx:Object firstName="Bill" lastName="Smith" companyID="11233"/>
<fx:Object firstName="Dave" lastName="Jones" companyID="13455"/>
<fx:Object firstName="Mary" lastName="Davis" companyID="11543"/>
<fx:Object firstName="Debbie" lastName="Cooper" companyID="14266"/>
</s:ArrayCollection>
</s:DataGrid>
<s:Label text="Selected index:"/>
<s:TextArea id="selIndex" height="50"/>
<s:Label text="Selected Last Name:"/>
<s:TextArea id="selLName" height="50"/>
</s:Application>
Use the selectionMode property of the DataGrid control to configure it for multiple selection. The default value of the selectionMode property is singleRow, which means that you can select only a single row at a time. Set the selectionMode property to multipleRows or to multipleCells to select multiple rows or cells.
Several properties of the DataGrid and Grid control multiple selection. These properties include the following:
selectedCells If the selectionMode property is multipleCells, a Vector of CellPosition objects containing the selected cell locations.
selectedIndices If the selectionMode property is multipleRows, a Vector of integers containing the indexes of the currently selected rows.
selectedItems If the selectionMode property is multipleRows, a Vector of data provider items corresponding to the currently selected rows.
For multiple selection, the set of selected cells or rows extends from the selection anchor to the last selected row or cell. The Grid.anchorRowIndex and Grid.anchorColumnIndex properties represent the location of the selection anchor.
The selectedIndex and selectedItem properties are valid in multiple selection mode. These properties contain information about the first cell or row selected in the list of currently selected items.
Click the first item, either a row or cell, to select it.
Hold down the Shift key as you select an additional item.
If the selectionMode property is set to multipleRows, click any cell in another row to select multiple, contiguous rows.
If the selectionMode property is set to multipleCells, click any cell to select multiple, contiguous cells.
Click the first item, either a row or cell, to select it.
Hold down the Control key (Windows) or the Command key (OSX) as you select an additional item.
If the selectionMode property is set to multipleRows, click any cell in another row to select that single row.
If the selectionMode property is set to multipleCells, click any cell to select that single cell.
The following example sets the selectionMode property to multipleCells. This application uses an event handler for the keyUp event to recognize the Control+C key combination and, if detected, copies the selected cells from the DataGrid control to your system's clipboard.
After you copy the cells, you can paste the cells in another location in the application, or paste them in another application. In this example, you paste them to the TextArea control located at the bottom of the application:
<?xml version="1.0" encoding="utf-8"?>
<!-- dpcontrols\sparkdpcontrols\SparkDGMultiSelect.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
import flash.events.KeyboardEvent;
import flash.system.System;
import spark.components.gridClasses.CellPosition;
import flash.ui.Keyboard;
// Event handler to recognize when Ctrl-C is pressed,
// and copy the selected cells to the system clipboard.
private function myKeyUpHandler(event:KeyboardEvent):void
{
if (event.ctrlKey && event.keyCode == Keyboard.C)
{
// Separator used between Strings sent to clipboard
// to separate selected cells.
const separator:String = ",";
// The String sent to the clipboard
var dataString:String = "";
// Loop over the selectedCells property.
// Data in selectedCells is ordered so that
// the last selected cell is at the head of the list.
const selectedCells:Vector.<CellPosition> = event.currentTarget.selectedCells;
const n:int = selectedCells.length;
for (var i:int = 0; i < n; i++)
{
// Get the cell position.
var cell:CellPosition = selectedCells[i];
// Get the row for the selected cell.
var data:Object =
event.currentTarget.grid.dataProvider[cell.rowIndex];
// Get the name of the field for the selected cell.
var dataField:String =
event.currentTarget.grid.columns[cell.columnIndex].dataField;
// Get the cell data using the field name.
dataString = data[dataField] + separator + dataString;
}
// Remove trailing separator.
dataString =
dataString.substr(0, dataString.length - separator.length);
// Write dataString to the clipboard.
System.setClipboard(dataString);
}
}
]]>
</fx:Script>
<s:DataGrid
selectionMode="multipleCells"
keyUp="myKeyUpHandler(event);">
<s:ArrayCollection>
<fx:Object>
<fx:Artist>Pavement</fx:Artist>
<fx:Price>11.99</fx:Price>
<fx:Album>Slanted and Enchanted</fx:Album>
</fx:Object>
<fx:Object>
<fx:Artist>Pavement</fx:Artist>
<fx:Album>Brighten the Corners</fx:Album>
<fx:Price>11.99</fx:Price>
</fx:Object>
</s:ArrayCollection>
<s:columns>
<s:ArrayCollection>
<s:GridColumn dataField="Artist"/>
<s:GridColumn dataField="Album"/>
<s:GridColumn dataField="Price"/>
</s:ArrayCollection>
</s:columns>
</s:DataGrid>
<s:TextArea id="myTA" text="Paste selected cells here ..."/>
</s:Application>
Depending on the selection mode of the DataGrid control, the caret is the row or cell that currently responds to keyboard input. The caret can be the currently selected cell or row, or a different cell or row. The Grid.caretRowIndex and Grid.caretColumnIndex properties represent the caret location.
Change the caret with a combination of the Control and Arrow keys. You can select the caret by pressing the Space key. If multiple selection is enabled, press the Space key to add the caret to the list of selected cells or rows. Toggle selection of the caret by using the Control-Space keys.
The following example uses the caretChange event and the selectionChange event to display the location of the caret and of the selected row:
<?xml version="1.0" encoding="utf-8"?>
<!-- dpcontrols\sparkdpcontrols\SparkDGCaret.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
height="450" width="450">
<s:layout>
<s:VerticalLayout paddingTop="5" paddingLeft="5"/>
</s:layout>
<fx:Script>
<![CDATA[
import spark.events.GridCaretEvent;
import spark.events.GridSelectionEvent;
import spark.components.Grid;
protected function selectionChangeHandler(event:GridSelectionEvent):void {
const eventGrid:Grid = event.currentTarget.grid;
selLabel.text = "The selected row is: " +
String(eventGrid.selectedIndex);
caretLabel.text = "The caret row is: " +
String(eventGrid.caretRowIndex);
}
protected function caretChangeHandler(event:GridCaretEvent):void {
const eventGrid:Grid = event.currentTarget.grid;
selLabel.text = "The selected row is: " +
String(eventGrid.selectedIndex);
caretLabel.text = "The caret row is: " +
String(eventGrid.caretRowIndex);
}
]]>
</fx:Script>
<s:Label id="selLabel"/>
<s:Label id="caretLabel"/>
<s:DataGrid id="myDG" width="100%"
selectionChange="selectionChangeHandler(event);"
caretChange="caretChangeHandler(event);">
<s:ArrayCollection>
<fx:Object firstName="Bill" lastName="Smith" companyID="11233"/>
<fx:Object firstName="Dave" lastName="Jones" companyID="13455"/>
<fx:Object firstName="Mary" lastName="Davis" companyID="11543"/>
<fx:Object firstName="Debbie" lastName="Cooper" companyID="14266"/>
</s:ArrayCollection>
</s:DataGrid>
</s:Application>
To see the difference between the selectedIndex and the caretIndex properties:
Select a row in the DataGrid control by clicking it. Notice that the selected row is also the caret, and that the selectedIndex and the caretIndex properties have the same value.
Use the Up Arrow and Down Arrow keys to move the selected row. Notice that the selectedIndex and the caretIndex properties have the same value.
With a row selected:
(On Windows) Hold down the Control key, and then use the Up Arrow and Down Arrow keys to move the caret.
(On OSX) Hold down the Command key, and then use the Up Arrow and Down Arrow keys to move the caret.
Notice that the control highlights the caret row, but the index of the selected row does not change. Press the Space key to select the caret row.
The Spark DataGrid can work with static data, meaning data that does not change at runtime. For example, you can define static data as an ArrayCollection of Objects. The following example defines static data in the DataGrid control:
<s:DataGrid> <s:dataProvider> <s:ArrayCollection> <fx:Object Artist="Pavement" Album="Slanted and Enchanted" Price="11.99" Cover="../assets/slanted.jpg"/> <fx:Object Artist="Pavement" Album="Brighten the Corners" Price="11.99" Cover="../assets/brighten.jpg"/> </s:ArrayCollection> </s:dataProvider> ... </s:DataGrid>
Dynamic data is data that can change at runtime. When dynamic data changes, you want to ensure that the DataGrid recognizes those changes so that it updates its display accordingly.
The item renderer and item editor mechanism used by the Spark DataGrid control relies on data binding to items in the data provider. Data binding is event driven. That means an item in the data provider must be able to dispatch events to indicate that the item has changed. By using the data binding mechanism, the DataGrid control can update its display at runtime when an item changes.
In the previous example that used static data, you used the Object class to define the items of the data provider. The Object class does not dispatch events when it changes and, therefore, does not support data binding. The compiler recognizes this situation and issues a warning when you compile the application. You can ignore that warning for applications that use static data.
One way to add event support to items in the data provider is to make sure the class that defines the items is a subclass of the flash.events.EventDispatcher class. Or, ensure that the class implements the event mechanism.
Flex provides the spark.utils.DataItem class that is a subclass of Object and supports events. Therefore, you can rewrite the previous example to use DataItem and support data binding, as shown below:
<s:DataGrid> <s:dataProvider> <s:ArrayCollection> <fx:DataItem Artist="Pavement" Album="Slanted and Enchanted" Price="11.99" Cover="../assets/slanted.jpg"/> <fx:DataItem Artist="Pavement" Album="Brighten the Corners" Price="11.99" Cover="../assets/brighten.jpg"/> </s:ArrayCollection> </s:dataProvider> ... </s:DataGrid>
Because the DataItem class can dispatch events when the data changes, you can modify the data at runtime and have those changes reflected in the DataGrid.
Alternatively, you can represent your data by creating a class that includes the [Bindable] metadata tag in the class definition. When you include the [Bindable] metadata tag, Flex automatically adds support for event dispatching to the class.
package myComponents
{
[Bindable]
public class MyBindableObj extends Object
{
public function MyBindableObj() {
super();
}
public var Artist:String;
public var Album:String;
public var Price:Number;
public var Cover:String;
}
}
By inserting the [Bindable] metadata tag before the class definition, you specify that all public properties support data binding. You can then use your custom class to define the data provider, as the following example shows:
<?xml version="1.0"?>
<!-- binding/SparkDGBindingClass.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:myComp="myComponents.*">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<s:DataGrid>
<s:dataProvider>
<s:ArrayCollection>
<myComp:MyBindableObj Artist="Pavement"
Album="Slanted and Enchanted"
Price="11.99"
Cover="../assets/slanted.jpg"/>
<myComp:MyBindableObj Artist="Pavement"
Album="Brighten the Corners"
Price="11.99"
Cover="../assets/brighten.jpg"/>
</s:ArrayCollection>
</s:dataProvider>
</s:DataGrid>
</s:Application>
You can create custom item renderers and item editors to control the display of the cells of the Spark DataGrid and Grid controls. You can also create custom item renderers for the header cells of each column of the grid.
You set a custom renderer or editor for each column of the grid. Use the GridColumn.itemRenderer, GridColumn.itemEditor, and GridColumn.headerRenderer properties to specify your custom renderer or editor.
You typically create custom item renderers and item editors in MXML. However, for the highest performance, create them in ActionScript.
Item and header renderers must implement the IGridItemRenderer interface. Item editors must implement the IGridItemEditor interface. The following table describes these interfaces:
|
Interface |
Implemented by |
Notes |
|---|---|---|
|
IGridItemRenderer |
Custom item and header renderers |
All custom item and header renderers must implement the IGridItemRenderer interface. The base interface of IGridItemRenderer is IDataRenderer, the interface implemented by item renderers for the Spark list-based controls. |
|
IGridItemEditor |
Custom item editors |
All custom item editors must implement the IGridItemEditor interface. The base interface of IGridItemEditor is IDataRenderer. |
When using the DataGrid control, you want to ensure the highest performance possible. One of the main factors affecting performance is the time required to render of each visible cell of the grid. Therefore, you want your item renderers to perform at the highest level.
Flex defines several item renderers that you can use to achieve high performance with the DataGrid control. By default, the DataGrid control uses the DefaultGridItemRenderer renderer. This renderer is written in ActionScript to provide good performance across all platforms.
The following table describes the item renderer classes that ship with Flex:
|
Item Renderer |
Use |
|---|---|
|
The default item renderer that displays the cell data in a text label using the UIFTETextField control. This class is not intended to be extended. Create a custom item renderer based on the GridItemRenderer class. Because it supports the Flash Text Engine (FTE), this item render also supports bidirectional text. |
|
|
Optimized for deployment on Microsoft Windows. For Windows, it provides improved performance over the DefaultGridItemRenderer. For other operating systems, use DefaultGridItemRenderer for best performance. Because it is based on the TextField component, this item renderer does not support bidirectional text. |
|
|
The base class for custom item renderers. This class implements the IGridItemRenderer interface. |
Item renderers for the Spark list-based controls, such as List, must implement the IDataRenderer interface. Item renderers for the Spark DataGrid must implement the IGridItemRenderer interface, which is derived from the IDataRenderer interface. Therefore, the process of creating an item renderer for the DataGrid is similar to creating one for the List control.
An item renderer is associated with a column of the DataGrid control. The item renderer then controls the appearance of each cell in the column. However, each item renderer has access to the data item for an entire row of the DataGrid control. Use the data property of the item renderer to access the data item.
By accessing the data item for the entire row, the item renderer can display multiple data fields, or display a single value created from multiple fields. For example, each row of the data provider for the DataGrid control in the following example contains four fields:
<?xml version="1.0" encoding="utf-8"?>
<!-- dpcontrols\sparkdpcontrols\SparkDGComplexIR.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
width="450" height="450">
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
// Data includes URL to album cover.
[Bindable]
private var initDG:ArrayCollection = new ArrayCollection([
{Artist:'Pavement', Album:'Slanted and Enchanted',
Price:11.99, Cover:'assets/slanted.jpg'},
{Artist:'Pavement', Album:'Brighten the Corners',
Price:11.99, Cover:'assets/brighten.jpg'}
]);
]]>
</fx:Script>
<s:DataGrid id="myGrid"
dataProvider="{initDG}"
variableRowHeight="true">
<s:columns>
<s:ArrayList>
<s:GridColumn dataField="Artist"/>
<s:GridColumn dataField="Album" itemRenderer="myComponents.DGComplexIR"/>
<s:GridColumn dataField="Price"/>
</s:ArrayList>
</s:columns>
</s:DataGrid>
</s:Application>
<?xml version="1.0" encoding="utf-8"?>
<!-- dpcontrols\sparkdpcontrols\myComponents\DGComplexIR.mxml -->
<s:GridItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:VGroup height="100" paddingTop="10">
<s:Label id="albumName"
width="100%"
text="{data.Album}"/>
<s:Image id="albumImage"
source="{data.Cover}"/>
</s:VGroup>
</s:GridItemRenderer>
Notice how the item renderer uses the data property of the item renderer to access the data item that corresponds to the entire row of the DataGrid control.
In the previous example, the item renderer was defined in a file separate from the main application file. You can define inline item renderers for the DataGrid control. By using an inline item renderer, your code can all be defined in a single file. To define an inline item renderer, you use the <fx:Component> tag. For example using inline item renderers, see Defining an inline item renderer for a Spark container.
The following example creates an inline item renderer by using the Spark Label control:
<?xml version="1.0" encoding="utf-8"?>
<!-- dpcontrols\sparkdpcontrols\SparkDGStyledIR.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
width="450" height="450">
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
// Data includes URL to album cover.
[Bindable]
private var initDG:ArrayCollection = new ArrayCollection([
{Artist:'Pavement', Album:'Slanted and Enchanted',
Price:11.99, Cover:'../assets/slanted.jpg'},
{Artist:'Pavement', Album:'Brighten the Corners',
Price:11.99, Cover:'../assets/brighten.jpg'}
]);
]]>
</fx:Script>
<s:DataGrid id="myGrid"
dataProvider="{initDG}"
variableRowHeight="true">
<s:columns>
<s:ArrayList>
<s:GridColumn dataField="Artist">
<s:itemRenderer>
<fx:Component>
<s:GridItemRenderer>
<s:Label id="labelDisplay" fontSize="24"/>
</s:GridItemRenderer>
</fx:Component>
</s:itemRenderer>
</s:GridColumn>
<s:GridColumn dataField="Album"/>
<s:GridColumn dataField="Price"/>
</s:ArrayList>
</s:columns>
</s:DataGrid>
</s:Application>
The DataGridSkin class uses the GridColumnHeaderGroup component to control the display of the column headers. The GridColumnHeaderGroup component displays a row of headers cells, where the vertical edges of the header cells are aligned with the grid columns.
The GridColumnHeaderGroup component arranges header renderer instances in a row, where the left and right edge of each renderer match the corresponding column. The renderers' height is the maximum preferred height for all of the displayed header renderers.
Like the Grid control and item renderers, the GridColumnHeaderGroup class only creates as many column header renderers and separators as are visible. Renderers and separators that have been scrolled out of view are recycled.
By default, the GridColumnHeaderGroup component uses the spark.skins.spark.DefaultGridHeaderRenderer class as the header renderer. To create a custom header renderer, define the renderer in MXML or ActionScript. Header renderers must implement the IGridItemRenderer interface.
Then, use the Grid.headerRenderer property to specify to use the custom renderer for the column.
The DataGrid control includes an editable property that you set to true to let users edit grid cells. By default, the value of the editable property is false, which means that you cannot edit the cells.
For a DataGrid control, setting the editable property to true enables editing for all columns of the grid. You can disable editing for any column by setting the GridColumn.editable property to false.
Item editing is cell based. To edit a cell, first select the cell or cell row, depending on the selection mode of the grid. Then select the cell to edit. If editing is enabled, an item editor appears over the selected cell.
All item editors must implement the IGridItemEditor interface. The GridItemEditor class implements the IGridItemEditor interface. GridItemEditor also adds the value property that you can use to pass data to and from the item editor. Most custom item editors are created as subclasses of GridItemEditor.
The two most important questions when dealing with an item editor are:
How do you pass data to the item editor?
Use the bindable GridItemEditor.value property to pass data to the item editor. The data type of the value property is Object, so you can use it to pass a single value to the item editor, or you can use it to pass multiple items as fields of the Object.
The GridItemEditor class implements the value property as a setter and a getter method. When the item editor is created, Flex calls the setter method, passing the cell data from the data provider item for the row. Typically, you override the setter method in your item editor to initialize any items in the item editor from the cell data. The value property only exists while the item editor is open.
To access the data provider element for the entire row, use the data property of the item renderer.
How do you pass data back to the DataGrid control from the item editor?
Use the GridItemEditor.value property to pass data back to the control. Typically, in your item editor you override the getter method for the value property to return any results back to the DataGrid control. The DataGrid control writes the returned value to the data field of the data provider element for the row that corresponds to the edited cell.
The item editor uses the IGridItemEditor.save() method to write the value property to the data provider of the DataGrid control. You can override the save() method to control how the value property is written to the data provider. For example, the item editor might return multiple values that you want to write to multiple fields of the data provider element for the row. Override the save() method in this situation to update the data provider.
Flex ships with two item editors that you can use in your application. The following table describes these item editor classes:
|
Item Editor |
Use |
|---|---|
|
spark.components.gridClasses.DefaultGridItemEditor |
Uses a Spark TextArea control to let you edit the text value of a cell. By default, the DataGrid control uses the DefaultGridItemEditor class. |
|
spark.components.gridClasses.ComboBoxGridItemEditor |
Uses a Spark ComboBox control to display a drop-down list of cell values. Select a value to set the new value of the cell. |
<?xml version="1.0" encoding="utf-8"?>
<!-- dpcontrols\sparkdpcontrols\SparkDGComboBoxIE.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
width="450">
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
[Bindable]
private var myDP:ArrayCollection = new ArrayCollection([
{label1:"Order #2314", quant:3, color:'red'},
{label1:"Order #2315", quant:3, color:'red'}
]);
]]>
</fx:Script>
<s:DataGrid id="myDG" width="100%"
dataProvider="{myDP}"
variableRowHeight="true"
editable="true" >
<s:columns>
<s:ArrayList>
<s:GridColumn dataField="label1" headerText="Order #"/>
<s:GridColumn dataField="quant" headerText="Qty"/>
<s:GridColumn dataField="color" headerText="Color">
<s:itemEditor>
<fx:Component>
<s:ComboBoxGridItemEditor>
<s:dataProvider>
<s:ArrayList>
<fx:String>red</fx:String>
<fx:String>green</fx:String>
<fx:String>blue</fx:String>
</s:ArrayList>
</s:dataProvider>
</s:ComboBoxGridItemEditor>
</fx:Component>
</s:itemEditor>
</s:GridColumn>
</s:ArrayList>
</s:columns >
</s:DataGrid>
</s:Application>
The following steps describe the lifecycle of an item editor:
An editing session begins in response to a user gesture, such as the user clicking a selected cell. You can also make an explicit call to the DataGrid.startItemEditorSession() method to start the editing session.
Before the item editor appears, the DataGrid dispatches the gridItemEditorSessionStarting event.
You can cancel the editing session by calling the preventDefault() method in the event handler for the gridItemEditorSessionStarting event.
Flex sets the rowIndex, column, and data properties of the item editor. The data property contains the data provider item for the entire row.
Flex sets the value property of the item editor to the value of the field in the data provider element that corresponds to the cell being edited.
Flex calls the IGridItemEditor.prepare() method.
When the prepare() method is called, the editor's size and location have been set and the editor's layout has been validated. You can override the prepare() method to make any final modifications to the editor, such as modifying its visual characteristics or attaching event handlers.
Flex makes the editor visible by setting its visible property to true.
The DataGrid dispatches the gridItemEditorStart event.
When the item editor is first displayed, it is given keyboard focus and its setFocus() method is called. You typically override the setFocus() method of the item editor to shift the focus to a specific component in the item editor.
The user interacts with the editor.
The edit session ends when the user presses the Enter key to save the data, or the Escape key to cancel the edit. The session also ends, and the data is saved, when the users clicks outside the editor, or the editor loses keyboard focus.
If the editing session is saved, Flex calls the IGridtemEditor.saved() method to write the value property back to the data provider.
You can end the editing sessions programmatically by calling the DataGrid.endEditorSession() method.
Flex calls the IGridtemEditor.discard() method.
Override the discard() method to reverse any settings you made in the prepare() method, such as removing event handles, or perform any other cleanup.
The DataGrid dispatches either the gridItemEditorSessionSave or gridItemEditorSessionCancel event.
<?xml version="1.0" encoding="utf-8"?>
<!-- dpcontrols\sparkdpcontrols\SparkDGItemEditor.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
width="450">
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
[Bindable]
private var myDP:ArrayCollection = new ArrayCollection([
{label1:"Order #2314", quant:3, Sent:true},
{label1:"Order #2315", quant:3, Sent:false}
]);
]]>
</fx:Script>
<s:DataGrid id="myDG" width="100%"
dataProvider="{myDP}"
variableRowHeight="true"
editable="true" >
<s:columns>
<s:ArrayList>
<s:GridColumn dataField="label1" headerText="Order #"/>
<s:GridColumn dataField="quant"
headerText="Qty"
itemEditor="myComponents.DGNumStepperEditor"/>
</s:ArrayList>
</s:columns >
</s:DataGrid>
</s:Application>
The DGNumStepperEditor.mxml item editor defines a NumericStepper control to set an integer value. The item editor overrides the setter method for the value property to initialize the NumericStepper control with the current value of the cell.
<?xml version="1.0" encoding="utf-8"?>
<!-- dpcontrols\sparkdpcontrols\myComponents\DGNumStepperEditor.mxml -->
<s:GridItemEditor xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Script>
<![CDATA[
// Override the setter to initialize the NumericStepper control
// with the cell data.
override public function set value(newValue:Object):void {
ns.value = newValue as Number;
}
// Override the getter to return the current value of
// the NumericStepper control.
// The save() method updates the data provider element for the
// row of the grid with this value.
override public function get value():Object {
return ns.value;
}
// Override setFocus() to shift focus to the NumericStepper.
override public function setFocus():void {
ns.setFocus();
}
]]>
</fx:Script>
<s:NumericStepper id="ns" width="100%"
fontWeight="bold"/>
</s:GridItemEditor>
The following table describes how the item editor responds to user interaction:
|
User interaction |
Response |
|---|---|
|
F2 |
If cell selection mode is enabled, edit the cell indicated by the caret. If row selection mode is enabled, and a cell has not been edited before, edit the first visible cell in the row indicated by the caret. Otherwise edit the cell in the last edited column in the caret row. |
|
Enter |
Save the editor's value and close the editor. |
|
Esc |
Cancel the editing session by closing the editor without saving the value. |
|
Tab |
Save the editor's value, close the editor, and open the editor in the next column that is editable. |
|
Shift+Tab |
Save the editor's value, close the editor, and open the editor in the first previous column that is editable. |
|
Ctrl+. |
Cancel the editing session by closing the editor without saving the value. |
|
Ctrl+Enter |
Save the editor's value, close the editor, and move selection to the same column in the next row. |
|
Ctrl+Shift+Enter |
Save the editor's value, close the editor, and move selection to the same column in the previous row. |
|
Single mouse click |
Open the editor in response to a single click on the selected cell. The cell must already be selected. If the Shift or Ctrl key is pressed when the click occurs, then the editor does not open because the Shift and Ctrl keys are used to modify the selection. |
By default, users can sort the row of a DataGrid by clicking the column headers. Clicking the column header initially sorts the display in descending order of the entries in the selected column, and clicking the header again reverses the sort order. For an example, see Sorting the columns of the Spark DataGrid control.
The GridColumn sortCompareFunction property lets you specify a custom comparison function used to sort the rows by that column. This property sets the compareFunction property of the default Spark SortField class object used by the DataGrid.
The sortCompareFunction property lets you specify the function that compares two objects and determines which would be higher in the sort order, without requiring you to explicitly create a Sort object on your data provider.
The comparison function passed to the sortCompareFunction property must have the following signature:
function sortCompareFunction(obj1:Object, obj2:Object, gc:GridColumn):int {
// Sort logic
}
The obj1 and obj2 arguments specify the objects to compare, and gc specifies the column of the DataGrid control to sort.
Flex ships with two collator classes to help you write your comparison function. The spark.globalization.MatchingCollator and spark.globalization.SortingCollator provide locale-sensitive string comparison functions.
By default, the sorting used by the DataGrid control is case sensitive. In the following example, you use the SortingCollator class to perform a case-insensitive comparison of two cells to sort the Name column of the DataGrid:
<?xml version="1.0" encoding="utf-8"?>
<!-- dpcontrols\sparkdpcontrols\SparkDGXMLSort.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
width="500" height="600">
<s:layout>
<s:VerticalLayout paddingTop="10"/>
</s:layout>
<fx:Declarations>
<fx:XMLList id="employees">
<employee>
<name>Joanne Wall</name>
<phone>555-219-2012</phone>
<email>jwall@fictitious.com</email>
<active>true</active>
</employee>
<employee>
<name>Mary Jones</name>
<phone>555-219-2000</phone>
<email>mjones@fictitious.com</email>
<active>true</active>
</employee>
<employee>
<name>mary jones</name>
<phone>555-219-2000</phone>
<email>mjones@fictitious.com</email>
<active>true</active>
</employee>
<employee>
<name>Maurice Smith</name>
<phone>555-219-2012</phone>
<email>maurice@fictitious.com</email>
<active>false</active>
</employee>
<employee>
<name>Dave Davis</name>
<phone>555-219-2000</phone>
<email>ddavis@fictitious.com</email>
<active>true</active>
</employee>
<employee>
<name>Tom Maple</name>
<phone>555-219-2000</phone>
<email>tmaple@fictitious.com</email>
<active>true</active>
</employee>
</fx:XMLList>
<s:XMLListCollection id="employees2" source="{employees}"/>
<s:XMLListCollection id="employees3" source="{employees}"/>
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
import spark.collections.Sort;
import spark.collections.SortField;
import spark.globalization.SortingCollator;
// Create an instance of the SortingCollator.
private var collator:SortingCollator = new SortingCollator();
// Define the sort compare function used by the first column.
private function sortCompareFunction(obj1:Object, obj2:Object, gc:GridColumn):int {
// Make the sort case insensitive. The default is case sensitive.
collator.ignoreCase = true;
return collator.compare(obj1[gc.dataField], obj2[gc.dataField]);
}
]]>
</fx:Script>
<s:Label text="Custom case insensitive sort of the Name colum"/>
<s:DataGrid id="dg" width="500" dataProvider="{employees2}">
<s:columns>
<s:ArrayList>
<s:GridColumn dataField="name" headerText="Name"
sortCompareFunction="sortCompareFunction"/>
<s:GridColumn dataField="phone" headerText="Phone"/>
<s:GridColumn dataField="email" headerText="Email"/>
</s:ArrayList>
</s:columns>
</s:DataGrid>
<s:Label text="Default case sensitive sort of the Name colum"/>
<s:DataGrid width="500" dataProvider="{employees3}">
<s:columns>
<s:ArrayList>
<s:GridColumn dataField="name" headerText="Name"/>
<s:GridColumn dataField="phone" headerText="Phone"/>
<s:GridColumn dataField="email" headerText="Email"/>
</s:ArrayList>
</s:columns>
</s:DataGrid>
</s:Application>
A DataGrid control displays a grid of rows and columns. Depending on the available screen space, all rows and columns might not be currently visible. Paging down through the data items displayed by a 10-row control shows items 0-9, 10-19, 20-29, and so on.
The user clicks individual data items to select them. If the DataGrid is configured for multiple selection, holds down Shift key while clicking to select multiple items.
The control has the following default keyboard navigation features:
|
Key |
Action |
|---|---|
|
Up Arrow |
Moves selection up one item. Hold down the Control key (Windows) or Command key (OSX) to only move the caret, but not change selection. |
|
Down Arrow |
Moves selection down one item. Hold down the Control key (Windows) or Command key (OSX) to only move the caret, but not change selection. |
|
Left Arrow |
In cell selection mode, moves selection one column to the left. Hold down the Control key (Windows) or Command key (OSX) to only move the caret, but not change the selected cell. |
|
Right Arrow |
In cell selection mode, moves selection one column to the right. Hold down the Control key (Windows) or Command key (OSX) to only move the caret, but not change the selected cell. |
|
Page Up |
Moves selection up one page. |
|
Page Down |
Moves selection down one page. |
|
Home |
Moves selection to the top of the grid. |
|
End |
Moves selection to the bottom of the grid. |
|
Control key (Windows) and Command key (OSX) and a navigation key |
Allows for multiple, noncontiguous selection and deselection in multiple selection mode. Works with Arrow keys, Page Up key, Page Down key, mouse click, and mouse drag. |
|
Shift key and a navigation key |
Allows for contiguous selection in multiple selection mode. Works with keypresses, click selection, and drag selection. Works with Arrow keys, Page Up key, Page Down key, mouse click, and mouse drag. |
|
Control-A |
Select all grid items |
|
Space |
Adds the caret to the selection list |
|
Control-Space |
Toggle the selection of the caret. |
|
Shift-Space |
Extends selection from the anchor to the caret |
Navigation
Adobe and Adobe Flash Platform are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States and/or other countries and are used by permission from Adobe. No other license to the Adobe trademarks are granted.