Products
Technologies

Developer resources

Creating an auto-scrolling DataGrid control in Flex

Avg. Rating 3.0

Problem

The following example shows how you can auto-scroll a Flex DataGrid control.

Solution

Listen for the ArrayCollection data provider object's collectionChange event, and set the verticalScrollPosition property to the maxVerticalScrollPosition property.

Detailed explanation

<?xml version="1.0" encoding="utf-8"?>
<!--http://blog.flexexamples.com/2009/01/31/creating-an-auto-scrolling-datagrid-control-in-flex/ -->
<mx:Application name="DataGrid_maxVerticalScrollPosition_text"
        xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white"
        creationComplete="init();">

    <mx:Script>
        <![CDATA[
            import mx.events.CollectionEvent;
            private var timer:Timer;

            private function init():void {
                timer = new Timer(500);
                timer.addEventListener(TimerEvent.TIMER, onTimer);
                timer.start();
            }

            private function onTimer(evt:TimerEvent):void {
                var now:String = new Date().toTimeString();
                arrColl.addItem({id:timer.currentCount, time:now});
            }

            private function arrColl_collectionChange(evt:CollectionEvent):void {
                callLater(autoScrollDataGrid);
            }

            private function autoScrollDataGrid():void {
                if (dataGrid) {
                    dataGrid.validateNow();
                    dataGrid.verticalScrollPosition = dataGrid.maxVerticalScrollPosition;
                }
            }
        ]]>
    </mx:Script>

    <mx:ArrayCollection id="arrColl"
            collectionChange="arrColl_collectionChange(event);" />

    <mx:DataGrid id="dataGrid"
            dataProvider="{arrColl}"
            verticalScrollPolicy="on"
            width="200"
            rowCount="8">
        <mx:columns>
            <mx:DataGridColumn dataField="id" width="50" />
            <mx:DataGridColumn dataField="time" />
        </mx:columns>
    </mx:DataGrid>

</mx:Application>

For more information, see "Creating an auto-scrolling DataGrid control in Flex" at FlexExamples.com.

Report abuse

Related recipes