Custom Sorting with ObjectListView

2019-02-15 13:40发布

问题:

Let's say I have an objectListView with 3 columns

ArticleNumber | OrderNumber | Status
 8080         | 123.456.789 | Delivered
 80           | 456.789.101 | Pending
 901          | 11.111.111  | Delivered

With the Automatic sorting, the smaller article number would go under the bigger article number, so it would either sort 8080, 80, 901 or 901, 80, 8080 but I want that the smallest number would be on top.

On OrderNumber the same.

And Status wouldn't work. On, it just sorts the ArticleNumber when I press the ColumnHeader so I'd like to sort the Status depending on the text.

I think I need a CustomSorter for that task but I couldn't find how to use it and I couldn't find a good example, the cookbook of OLV didn't help me.

Do you have an Example for me how this could be done?

回答1:

Example using a custom sorter:

MyOlv.CustomSorter = delegate(OLVColumn column, SortOrder order) {
    // check which column is about to be sorted and set your custom comparer
    if (column == ArticleNumber) {
        MyOlv.ListViewItemSorter = new ArticleNumberComparer(order);
    }
};          

class ArticleNumberComparer : IComparer {
    SortOrder _Order;

    public ArticleNumberComparer(SortOrder order) {
        _Order = order;
    }

    public int Compare(object x, object y) {
         // perform you desired comparison depending on the _Order
    }
}

Note that x and y in Compare() are of type ListViewItem. You can take a look at this on how to access the underlying model objects.