C# – Sorting custom columns in a DataGridView bound to a BindingList

bindinglistcdatagridviewsorting

I have a DataGridView which is data-bound to a BindingList. My DataGridView also has a couple of custom columns that I have added. These are not data-bound, but rather are generated based on items in my BindingList (ie: an item in my BindingList of type A has a property of type B; my custom column shows B.Name (EDIT: In this case, "Name" is a property of the class B, and thus the property represented by the column is not directly found in the items in the BindingList)).

I need to be able to sort all of the columns in my DataGridView. DataGridView has two sort methods: Sort(IComparer), and Sort(DataGridViewColumn, ListSortDirection). I use the second one to sort my data-bound columns, but it of course throws an exception when used on a non-data-bound column. The first method will throw an exception if DataSource is not null.

So neither of DataGridView's built-in Sort methods will work as far as I can tell. How else can I sort my grid based on my custom columns?

EDIT:

What I do at the moment is handle the click on the column header, following the instructions seen here: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.columnheadermouseclick.aspx

The problem arises on the line:

dataGridView1.Sort(newColumn, direction);

Things work great when newColumn holds one of the properties of an object in my BindingList. But in order to sort one of my custom columns, I will have to avoid this line altogether, and find some other way to sort the data grid based on that column. Does that mean having to build my own sort function? That seems like it may be a humongous pain.

Best Answer

FINAL Edit/Answer: I can't think of a way to do this while still using the sorting mechanism built into the DataGridView. If I were in your shoes, I would probably just change the SortMode of each column to "Programmatic" and then handle the "ColumnHeaderMouseClick" yourself. At that point you should call a sort method in your modified BindingList class which will perform the sorting as necessary according the which column was clicked. This avoids using the Sort method of the DGV and sorts the underlying list directly.

Full Discourse Located in the comments section. Original Answer follows immediately:

EDIT: Due to some confusion about the problem and subsequent discussion about it, I have a new suggestion down in the comments of this Answer. I'm leaving the original answer I posted so that we can reference it.

I recently had to do this - and I won't lie it was a real pain. I did come up with a solution (with help from some friends here at SO) so here goes. I created a new IComparer based interface that allows you to specify both a column and a direction. I only did this because I need my sorting code to be as generic as possible - I have TWO grids that need to sort like this, and I don't want to maintain twice the code. Here is the interface, quite simple:

   public interface IByColumnComparer : IComparer
   {
      string SortColumn { get; set; }
      bool SortDescending { get; set; }
   }

Obviously, if you're not worried about keeping things generic (you probably should) than this isn't strictly necessary. Then, I built a new class that is based on BindingList<>. This allowed me to override the sorting code and provide my own IByColumnComparer on a column by column basis which is what allowed for the flexibility I needed. Check this out:

public class SortableGenericCollection<T> : BindingList<T>
{
  IByColumnComparer GenericComparer = null; 

  public SortableGenericCollection(IByColumnComparer SortingComparer)
  {
     GenericComparer = SortingComparer;
  }


  protected override bool SupportsSortingCore
  {
     get
     {
        return true;
     }
  }

  protected override bool IsSortedCore
  {
     get
     {
        for (int i = 0; i < Items.Count - 1; ++i)
        {
           T lhs = Items[i];
           T rhs = Items[i + 1];
           PropertyDescriptor property = SortPropertyCore;
           if (property != null)
           {
              object lhsValue = lhs == null ? null :
              property.GetValue(lhs);
              object rhsValue = rhs == null ? null :
              property.GetValue(rhs);
              int result;
              if (lhsValue == null)
              {
                 result = -1;
              }
              else if (rhsValue == null)
              {
                 result = 1;
              }
              else
              {
                 result = GenericComparer.Compare(lhs, rhs); 
              }
              if (result >= 0)
              {
                 return false;
              }
           }
        }
        return true;
     }
  }

  private ListSortDirection sortDirection;
  protected override ListSortDirection SortDirectionCore
  {
     get
     {
        return sortDirection;
     }
  }

  private PropertyDescriptor sortProperty;
  protected override PropertyDescriptor SortPropertyCore
  {
     get
     {
        return sortProperty;
     }
  }

  protected override void ApplySortCore(PropertyDescriptor prop,
  ListSortDirection direction)
  {
     sortProperty = prop;
     sortDirection = direction;

     GenericComparer.SortColumn = prop.Name;
     GenericComparer.SortDescending = direction == ListSortDirection.Descending ? true : false;

     List<T> list = (List<T>)Items;
     list.Sort(delegate(T lhs, T rhs)
     {
        if (sortProperty != null)
        {
           object lhsValue = lhs == null ? null :
           sortProperty.GetValue(lhs);
           object rhsValue = rhs == null ? null :
           sortProperty.GetValue(rhs);
           int result;
           if (lhsValue == null)
           {
              result = -1;
           }
           else if (rhsValue == null)
           {
              result = 1;
           }
           else
           {
              result = GenericComparer.Compare(lhs, rhs);
           }
           return result;
        }
        else
        {
           return 0;
        }
     });
  }

  protected override void RemoveSortCore()
  {
     sortDirection = ListSortDirection.Ascending;
     sortProperty = null;
  }
}

Now, as you can see in the ApplySortCore method, I am receiving the column and the direction directly from the DataGridView - meaning that I am not calling this programmatically. That doesn't sound like what you want to do, but you could easily modify this code if you need to call it programmatically and pass the appropriate IByColumnComparer. My point in showing you all this is so you can understand how to modify the sorting algorithm, which is quite useful.

Special thanks to @MartinhoFernandes for the suggestions concerning making this class more generic.

Related Topic