views:

308

answers:

2

Hi,

I am trying to create a dynamic datagrid in Flex 3, I have a list of columns a list of objects which correspond to datapoints for those columns which I fetch from a url. While the grid works perfectly fine the problem is that sorting on the columns is done in lexical order.

I am aware that this can be fixed by adding a sortcomparefunction to a column, which is not easy for this case. I have tried doing

            var dgc:DataGridColumn = new DataGridColumn(dtf);
            f1[dtf] = function(obj1:Object, obj2:Object):int {
               return Comparators.sortNumeric(obj1[dtf],obj2[dtf]);
            };
            dgc.sortCompareFunction = f1[dtf];`

But the problem is that the function object that I am creating here is being overwritten in every iteration (as I am adding columns) and eventually all the columns will have sorting done only on the last column added.

Suggestions please.

A: 

I've got the exact same issue and nothing on google to help me :

var dgc:DataGridColumn = new DataGridColumn(); dgc.sortCompareFunction = function sortStringOrNumber(obj1:Object, obj2:Object):int { trace(dgc.dataField); return 1; }; ...

the dgc.dataField is always the same, doesn't matter the column I clicked on !! How can I get the selected dataGridColumn I clicked on ?

Antoine R
wrap the sort compare function that you are writing here in a separate class which has a field with to keep the value of dataField and a non static method to compare and give the result.It worked for me
Tom
Thanks Tom, your comment was very useful!
zdmytriv
A: 

Lets assume you have dynamicColumns array of some objects that you want create datagrid columns from.

var columns:Array = new Array();    
for (var i:int = 0; i < dynamicColumns.length; i++) {
    var column:DataGridColumn = new DataGridColumn(dynamicColumns[i].label);

    var dataGridColumnSortingHelper:DataGridColumnSortingHelper = new DataGridColumnSortingHelper(column);
    column.sortCompareFunction = dataGridColumnSortingHelper.columnSortCompareFunction;
    columns.push(column);
}
yourDataGrid.columns = columns;

Where DataGridColumnSortingHelper is like this:

public class DataGridColumnSortingHelper
{
    private var column:DataGridColumn;

    // Constructor
    public function DataGridColumnSortingHelper(column:DataGridColumn)
    {
        this.column = column;
    }

    // Public Methods
    public function columnSortCompareFunction(item1:Object, item2:Object):int
    {
        // define your custom function here and use column field to know what column you sorting by...

        return 0;
    }
}

Thanks Tom for comment.

zdmytriv