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

10 Responses 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!…

  2. Sameer Says:

    Hi! Thanks for sharing it was pretty helpful..I was also looking for the same solution. I am also planning to add more items to the context menu like Add/Edit/Delete data from DataGrid.

  3. Saurav Says:

    Hi, Thanks. Iwa trying to implement this for a lon time…

  4. Nick Says:

    Very cool! A lot simpler than I thought.

  5. Jim Says:

    Hi. I am new to Flex and would love to implement this in a project. Do you have any sample code for the complete application, or any help in where your code would live within the app?


  6. Eric Says:

    How do you attach the context menu to the header?

  7. Dong Duc Says:

    Thanks.that’s useful info for me.

  8. MPS Says:

    Thanks ! I would also like to know how to attach the context menu to the DataGrid header.

  9. nag Says:

    i want the same functionality in web application………
    and also i want to know how to add context menu to header

  10. matt Says:

    This won’t work in web applications because AIR handles menus differently.

Leave a Reply