Adding a ContextMenu to a DataGrid component is a simple enough task. Accessing the data from the row you right-clicked on is another matter. Logically (to my mind) the ContextMenuEvent should contain a reference to the DataGrid, and it does (contextMenuOwner). Search through your debugger, however, and you’ll quickly discover the DataGrid has not set it’s selectedItem object yet. There is a protected property called lastHighlightItemRenderer, but apparantly Adobe doesn’t feel that’s information you should be privy to. To solve this issue and access the row information under your mouse at the instance right-click is performed, you’ll need to do a little extra work.
private var dgContextMenu:ContextMenu; private var lastRollOverIndex:Number; private function init():void { dgContextMenu = new ContextMenu(); dgContextMenu.addEventListener(ContextMenuEvent.MENU_SELECT, menuSelectHandler); var menuItemEdit:ContextMenuItem = new ContextMenuItem("Edit Job"); dgContextMenu.customItems.push(menuItemEdit); menuItemEdit.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, menuItemEditSelectHandler); grid.contextMenu = dgContextMenu; } private function menuSelectHandler(event:ContextMenuEvent):void { grid.selectedIndex = lastRollOverIndex; } private function menuItemEditSelectHandler(event:ContextMenuEvent):void { var data:Object = grid.selectedItem; }
The trick to this code is in the menuSelectHandler function. That function is ran immediately on the right-click of the mouse and therefore sets up your DataGrid.selectedIndex property. The next issue you need to solve is how to keep lastRollOverIndex in sync with where your mouse is. To do that, code the rollOver event of the DataGrid to update that value.
<mx:DataGrid id="grid" width="100%" height="100%" dataProvider="{jobs}" itemRollOver="lastRollOverIndex = event.rowIndex"> <mx:columns> <mx:DataGridColumn headerText="Column One" dataField="columnOneData"/> <mx:DataGridColumn headerText="Column Two" dataField="columnTwoData"/> </mx:columns> </mx:DataGrid>
Interesting
Hello, i read your blog from time to time and i own a similar one and i was just wondering if you get
a lot of spam feedback? If so how do you prevent it, any plugin or anything you can suggest?
I get so much lately it’s driving me mad so any assistance is very much appreciated.
I’ve not had any issues with spam. Sorry to hear of your troubles.