Axarydax
Axarydax

Reputation: 16603

Force BindingList to sort

Is there a way to force a BindingList to sort (in an unit test)? According to the documentation, the method ApplySortCore is marked as protected, but there must be some way that the bound controls raise call that, isn't there?

I could always do it with reflection, but I try to avoid it if there is an acceptable solution.

Upvotes: 1

Views: 2663

Answers (3)

dinozaver
dinozaver

Reputation: 137

If you only need to sort the list at the beginning of the program, you can write objects into a List<>, then sort this list, and then change it to BindingList<>. I wanted to sort users by their name:

List<User> users_list = new List<User>();
... add users ...
BindingList<User> users_bindingList= new BindingList<User>(users_list.OrderBy(x => x.name).ToList());

And i then proceeded using this users_bindingList.

Upvotes: 0

Magnus
Magnus

Reputation: 46929

If you have your own derived SortableBindingList you can cast it to IBindingList and do:

((IBindingList)myList).ApplySort(prop, direction);

Upvotes: 4

Nzall
Nzall

Reputation: 3555

As mentioned on that page you linked:

The BindingList<T> class does not provide a base implementation of sorting, so ApplySortCore always throws a NotSupportedException by default. To enable sorting, derive from BindingList and perform the following tasks:

  • Override ApplySortCore and implement sorting, raising the ListChanged event when sorting is complete.
  • Override RemoveSortCore and implement sort removal.
  • Override SupportsSortingCore and set SupportsSortingCore to true.

In addition, you may want to implement the supplemental SortDirectionCore and SortPropertyCore sorting properties.

The problem is that the BindingList<T> Does not know how to sort objects of type T by default, because T can be a complex object with no immediately obvious method to sort. Also, ApplySortCore should Sort based on whatever property the user wants, and you need to explain how to do that.

So you need to derive a SortableBindingList<T>, in which you override the above methods.

Upvotes: 1

Related Questions