WinForms

Creating a sortable BindingList

No Comments »Written on September 10th, 2007 by
Categories: WinForms

Suppose you want to bind a collection of your custom objects to a DataGridView in a WinForm, and you want it to be sortable without having to write a lot of code. Once again, using Marc Brooks' DynamicComparer this becomes an easy task. Especially when you combine it with the BindingList class (which is a default implementation of the IBindingList interface):

    public class SortableBindingList<T> : BindingList<T>

    {

        private List<T> _sortableList;

 

        public SortableBindingList(List<T> list)

            : base(list)

        {

            _sortableList = list;

        }

 

        protected override bool SupportsSortingCore

        {

            get { return true; }

        }

 

        protected override void ApplySortCore(PropertyDescriptor property,

                                              ListSortDirection direction)

        {

            string sortExpression = property.Name;

 

            if (direction == ListSortDirection.Descending)

            {

                sortExpression = sortExpression + " DESC";

            }

 

            DynamicComparer<T> comparer =

                new DynamicComparer<T>(sortExpression);

 

            _sortableList.Sort(comparer.Comparer);

        }

 

        protected override void RemoveSortCore() {}

    }

Binding a sortable list to a DataGridView is now as easy as this:

            dataGridView.DataSource = new SortableBindingList<Order>(OrderService.GetAllOrders());

Obviously, the sorting capabilities are pretty basic... only one column at a time, sorting can't be removed, etc... For a lot of scenario's though, this could already be sufficient