Context menu for DataGrid rows

01 September 2007 | AIR / Apollo,Blogroll,flash,flex | Tags: , ,

UPDATE: In Flex beta3 mouseTraget is set for a MENU_SELECT-event, but not for a MENU_ITEM_SELECT.

Workaround: Save the mouseTarget in MENU_SELECT and reuse it in its consecutive MENU_ITEM_SELECT event.

UPDATE: this will not work with AIR beta2: mouseTarget is null for MENU_SELECT_ITEM and MENU_SELECT in AIR BETA2. I’ve filed a bug at Adobe.

If you add a custom context menu to a datagrid you most certainly want to know which row the context menu was opened for.

Flex has support for this:

ctxAdd = new ContextMenuItem( 'add row');
ctxAdd.addEventListener( ContextMenuEvent.MENU_ITEM_SELECT, handleRowAdd);


protected function handleRowAdd( evt:ContextMenuEvent):void {
var temp:int;
// check if a _row_ is clicked (else is for empty rows of datagrid)
if ( evt.mouseTarget is IListItemRenderer) temp = data_grid.itemRendererToIndex( evt.mouseTarget as IListItemRenderer);
else temp = 0;
addRow( temp);
}

MENU_ITEM_SELECT.mouseTarget is a DataGridItemRenderer when clicked on a row. With DataGrids’s itemRendererToIndex(…) we convert it to the corresponding row’s index.


2 Responses to “Context menu for DataGrid rows”

  • 1 LePrau Says:

    It worked for me with:
    ——————

    dataGridContextmenu = new ContextMenu();
    var menuItems:Array = [];
    var removeRow:ContextMenuItem = new ContextMenuItem(“Löschen”);
    removeRow.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, datagridContextMenuRightClick);
    menuItems.push(removeRow);
    dataGridContextmenu.customItems = menuItems;
    ———————-

    and later on this function:
    ———————-
    protected function datagridContextMenuRightClick(e:ContextMenuEvent):void {
    var mt:DataGridItemRenderer = e.mouseTarget as DataGridItemRenderer;
    var dataIndex:int = resultsGrid.itemRendererToIndex(mt);
    // resultsGrid => enter YOUR dataGrid-ID, and chose YOUR field index instead of .id
    var dataContent:String = resultsGrid.dataProvider[dataIndex].id;
    trace(“ID of data selected: “+dataContent);
    }
    ——————————

    Hope this helps ;)

  • 2 dragos Says:

    Cool

Leave a Reply