Creating an auto-scrolling DataGrid control in Flex

In a previous example, “Auto-scrolling a TextArea control in Flex”, we saw how you can auto-scroll a Flex TextArea control when new content is added by setting the verticalScrollPosition property to the value of the maxVerticalScrollPosition property.

The following example shows how you can auto-scroll a Flex DataGrid control using the ArrayCollection object’s collectionChange event, and the verticalScrollPosition and maxVerticalScrollPosition properties.

<?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>

View source is enabled in the following example.

11 thoughts on “Creating an auto-scrolling DataGrid control in Flex

    1. Creator is lazy, and didn’t have time to create Builder projects, export release builds, FTP files, link examples, etc.
      But, on a positive note, I have been going back through older Flex 4 examples and updating them to the latest API and in several cases added SWFs.

      Peter

  1. Great example.
    However, I have got an embarrassing situation where one of the column has long text (say 3 or 4 lines). what will happen is that the maxVerticalScrollPosition does not apply. it can’t show the bottom of the datagrid anymore!!!

Comments are closed.