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

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.

6 thoughts on “Detecting when the data provider of a DataGrid control changes in Flex

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

  2. Peter,

    Thank you for all your examples. I’ve been thrown head first into a Flex project. While loving it, I have hit a wall.

    I have populated a datagrid (dgA) via a local SQLite DB table called “assets”. I can add, edit and delete records fine from this table. Now I am trying to drag & drop a record from my populated datagrid (dgA) to an empty datagrid (dgB) (think shopping cart). The empty datagrid’s dataprovider is pointing to an empty table in my SQLite DB called “my_assets”. I cannot seem to update the “my_assets) table when the empty datagrid has a record added to it. I’ve been banging my head on this problem for two days. A few of your examples and other tutorials found on the cookbook get me close, but I am unable to make the darn thing work as a whole.

    Thanks again!
    Nate

Comments are closed.