Detecting when the data provider of a DataGrid control changes in Flex

by Peter deHaan on December 16, 2008

The following example shows how you can determine when the data provider of a Flex DataGrid control changes by listening for the collectionChange event (using the CollectionEvent.COLLECTION_CHANGE constant).

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/12/16/detecting-when-the-data-provider-of-a-datagrid-control-changes-in-flex/ -->
<mx:Application name="DataGrid_collectionChange_test"
        xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white"
        initialize="init();">

    <mx:Script>
        <![CDATA[
            import mx.controls.Alert;
            import mx.events.CollectionEvent;

            private function init():void {
                dataGrid.addEventListener(CollectionEvent.COLLECTION_CHANGE, dataGrid_collectionChange);
            }

            private function btn_click(evt:MouseEvent):void {
                var fontArr:Array = Font.enumerateFonts(true);
                dataGrid.dataProvider = fontArr.sortOn("fontName");
            }

            private function dataGrid_collectionChange(evt:CollectionEvent):void {
                Alert.show("The DataGrid control's data provider has changed.", evt.type);
            }
        ]]>
    </mx:Script>

    <mx:ApplicationControlBar dock="true">
        <mx:Button id="btn"
                label="Click me to set DataGrid data provider"
                click="btn_click(event);" />
    </mx:ApplicationControlBar>

    <mx:DataGrid id="dataGrid"
            width="400" />

</mx:Application>

View source is enabled in the following example.

{ 3 comments… read them below or add one }

Gareth Arch December 23, 2008 at 9:36 am

So it’s the actual control that the event listener should be attached to. I had been attaching it to the arraycollection and listening for the change there. Good to know why that wasn’t working :)
Thanks.

Reply

Kamuizero September 21, 2009 at 9:17 am

Thank you very much!

This example was precisely what I was looking for, helped me a lot :)

Reply

Kusmanto June 23, 2010 at 7:41 pm

Thank you. This code is what I was looking for a couple of days ago.

Reply

Leave a Comment

Sorry, this blog is terrible at eating HTML comments.
If you're pasting any HTML/XML/MXML code, you need to convert your < characters to &lt; and your > characters to &gt; .

Anti-Spam Protection by WP-SpamFree

Previous post:

Next post: