Hiding Flex DataGrid columns using a context menu in AIR

A Flex/AIR project I’m working on at the moment uses a DataGrid to display a lot of data. There needs to be lots of columns, but this means that the view can be a bit cluttered. What I wanted was an easy for the user to show or hide columns as they prefer. In Cocoa on Mac OS X you can right-click (or ctrl-click) to show a context menu to do this, which seems to be a good way. I thought there may be a way of doing this in Flex, but there didn’t appear to be. It was quite simple to implement and could be useful in lots of cases, so I thought I’d share the code. I put this in a creationComplete handler.

I’ve attached it as a context menu on the DataGrid, but you could also attach it to the header or to a button. I hope it helpful to someone.

var context:NativeMenu = new NativeMenu();
for each (var col:DataGridColumn in myDataGrid.columns){
	var menuI:NativeMenuItem = new NativeMenuItem(col.headerText);
	menuI.checked = col.visible;
	menuI.data = col;
	context.addItem(menuI);
}
context.addEventListener(Event.SELECT, function(e:Event):void {
	var t:NativeMenuItem = e.target as NativeMenuItem;
	t.checked = !t.checked;
	t.data.visible = t.checked;
});
 
myDataGrid.contextMenu = context;

One Response to “Hiding Flex DataGrid columns using a context menu in AIR”

  1. blog Says:

    Hiding Flex DataGrid columns using a context menu ……

    Bookmarked your post over at Blog Bookmarker.com!…

Leave a Reply