Skip to main content

Retain Scroll Position when changing the dataprovider of a spark flex4.5 datagrid

How The Code Works
The code is pretty simple. You instantiate a class level variable to hold the current location of the scroll bar. propertyChangeHandler() updates that variable and when the dataprovider is changed the grid is scrolled down to the last value of the variable i.e the last location of the scroll bar.

private var scrollerPosition:Number=0;
private var _gridDP:XMLListCollection;

function get GridDataProvider():XMLListCollection{
return this._gridDP;

public function set GridDataProvider(value:XMLListCollection):void{
this._gridDP = value;
public function group1_creationCompleteHandler(event:FlexEvent):void

private function propertyChangeHandler(e:PropertyChangeEvent):void {
if ( == "verticalScrollPosition" || == "horizontalScrollPosition")
trace("scroll position changed");
var curScrollPosition:Number = e.newValue as Number;
if(curScrollPosition !=0)
this.scrollerPosition = curScrollPosition;

private function setGridScrollPosition(event:Event):void{
gridMain.grid.verticalScrollPosition = this.scrollerPosition;


<s:DataGrid id="gridMain" dataProvider="{GridDataProvider}" width="100%" height="100%" fontSize="18" >