Selecting cells and rows in the Spark DataGrid control

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.

Handling selection events

Interactive changes to selection performed with a mouse or keyboard are processed in three steps:
  1. 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.

  2. If the selectionChanging event is not canceled, the control dispatches a selectionChange event to indicate that the selection change has been committed.

  3. 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.

Handle single cell and single row selection in the spark DataGrid control

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.

Note: While the selectedCell, selectedIndex, and selectedItem properties are all writable, Adobe recommends that you use methods of the DataGrid to change selection programmatically.

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>

The executing SWF file for the previous example is shown below:

Handle multiple cell and multiple row selection in the Spark DataGrid control

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.

Note: While the selectedCells, selectedIndices, and selectedItems properties are all writable, Adobe recommends that you use methods of the DataGrid to change selection programmatically.

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.

Select contiguous items in the control

  1. Click the first item, either a row or cell, to select it.

  2. 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.

Select discontiguous items in the control

  1. Click the first item, either a row or cell, to select it.

  2. 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.

Note: You can also use the keyboard to select multiple contiguous or discontiguous items. For information on keyboard navigation, see Spark DataGrid control keyboard shortcuts.

Example: Spark DataGrid using multiple selection

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>

The executing SWF file for the previous example is shown below:

Working with the caret in the Spark DataGrid control

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>

The executing SWF file for the previous example is shown below:

To see the difference between the selectedIndex and the caretIndex properties:

  1. 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.

  2. 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.

  3. 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.