apache flex – Keep selection when refreshing datagrid in ActionScript – Education Career Blog

I’m working on my first ever AIR application with flashbuilder – just so you know.

I’ve bound a mx:DataGrid component to a DataProvider which is a mx:HTTPService fetching an xml file with items. To keep the data up to data I’m polling the webservice on a given interval.

My problem is that I loose the currently selected item in my DataGrid when the data is updated. I’ve tried to save the DataGrid.selectedIndex and set when the data is updated, but I’m not sure when to do it?! The closest I’ve come is to restore the index when the updateComplete event of DataGrid is fired. This works, but the selection first fades away and then fades in – not updated soon enough.

So what is the best way to keep the selection? (only one selected item at a time)

And as a side question: is there a convenient way to only update the data when it has actually changed?

Thankful for any suggestions!


I’ll start from the bottom, the only way to only update the data when it has changed is to pass a check on the data on the server side to see if data has changed and make that a call before the actual update. So in short, you make two calls, one to see if the data has changed, which is a server side query, and the next only if that returns true, which updates the data.

Alternatively, you can also get the update, and compare it to your current data, and only update the UI if that data is different, but I have a feeling you mean the former answer of only doing the update CALL at all, if the data has changed.

As for the other solution, after you’ve saved the selectedIndex, do this inside your updateComplete:

private function yourDataGridUpdateComplete(event:FlexEvent):void{ 
    yourDataGrid.selectedIndex = yourIndex;


The DG uses the UUID of the data items to determine whether the item should be still selected after a refresh. If the data items don’t implement IUID they basically get random values created each time they are added to the DG.

If your data items implement the IUID and you use a consistent value (DB sequence number for example) the DG will “know” that after a refresh, the data item is the same one as before.

Leave a Comment