Maintain sort on a DataGrid when the dataProvider is changed

Usually, in our Flex application we do have a data-grid. This component is very useful for displaying data and have a sorting, ordering of columns and more, out of the box.

I can speak for my applications and say that every enterprise application I have ever build had at least one or more data-Grid’s inside it.

So, what can we say about a grid that has not been said before in the past…?

I recently had a grid that I enabled sorting on it. It had a data-Provider (ArrayCollection) and I needed to preserver the sorting when the collection had changed.

The default behavior when you hookup a collection to the dataProvider property of the grid, is that when the collection changes, it will change the sorting back to default.

This is the code before the fix:

[as3]

<mx:DataGrid width=“100%”

height=“100%”

id=“dataGrid”

dataProvider=“{myHelper.widgetModel.data}”

itemClick=“myHelper.updateCustomFieldsButtonBar()”

allowMultipleSelection=“true”

updateComplete=“myHelper.gridUpdateComplete(event)”>

mx:columns

/mx:columns

/mx:DataGrid

[/as3]

This peace of code it the most important peace in the puzzle, wiring up (binding) between a model (collection) and the dataProvider:

[as3]

dataProvider=“{myHelper.widgetModel.data}”

[/as3]

So, we know that this way does not work.

What do we need to do in order to save the sorting when the provider changes?

What we actually need to do is to create a view of our collection, provide it with data and wire it up to the grid

This is how we do it.

[as3]

<mx:DataGrid width=“100%”

height=“100%”

id=“dataGrid”

dataProvider=“{listCollectionView}”

itemClick=“myHelper.updateCustomFieldsButtonBar()”

allowMultipleSelection=“true”

updateComplete=“myHelper.gridUpdateComplete(event)”>

mx:columns

/mx:columns

/mx:DataGrid

[/as3]

Notice that the grid’s data provider is not the collection view.

Now, when the data will change, the sorting will not change.

Good luck!

Submit to Hacker News

[NOTE] This post has been imported to Hugo from a Wordpress blog. It may be broken, missing images, code snippets or other information.

[NOTE] updated September 5, 2010. It's 3067 days old . This article may have outdated content.