I'd suggest to use that class:
SortableBindingList<T> (for Windows.Forms)[
^]
Here is a copy of that class:
public class SortableBindingList<T> : BindingList<T> where T : class
{
private bool _isSorted;
private ListSortDirection _sortDirection = ListSortDirection.Ascending;
private PropertyDescriptor _sortProperty;
public SortableBindingList()
{
}
public SortableBindingList(IList<T> list)
:base(list)
{
}
protected override bool SupportsSortingCore
{
get { return true; }
}
protected override bool IsSortedCore
{
get { return _isSorted; }
}
protected override ListSortDirection SortDirectionCore
{
get { return _sortDirection; }
}
protected override PropertyDescriptor SortPropertyCore
{
get { return _sortProperty; }
}
protected override void RemoveSortCore()
{
_sortDirection = ListSortDirection.Ascending;
_sortProperty = null;
_isSorted = false;
}
protected override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction)
{
_sortProperty = prop;
_sortDirection = direction;
List<T> list = Items as List<T>;
if (list == null) return;
list.Sort(Compare);
_isSorted = true;
OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
}
private int Compare(T lhs, T rhs)
{
var result = OnComparison(lhs, rhs);
if (_sortDirection == ListSortDirection.Descending)
result = -result;
return result;
}
private int OnComparison(T lhs, T rhs)
{
object lhsValue = lhs == null ? null : _sortProperty.GetValue(lhs);
object rhsValue = rhs == null ? null : _sortProperty.GetValue(rhs);
if (lhsValue == null)
{
return (rhsValue == null) ? 0 : -1;
}
if (rhsValue == null)
{
return 1;
}
if (lhsValue is IComparable)
{
return ((IComparable)lhsValue).CompareTo(rhsValue);
}
if (lhsValue.Equals(rhsValue))
{
return 0;
}
return lhsValue.ToString().CompareTo(rhsValue.ToString());
}
}
[EDIT]
According to the discussion under this solution, especially to this:
User-15670402 wrote:
SortableBindingList<ArtistList> xList = new SortableBindingList<ArtistList>();
xList = (from a in context.Artists
orderby a.BirthName
select new ArtistList
{
ArtistId = a.ArtistId,
Last_Name = a.BirthName.Split(space).Last(),
Age = DateTime.Today.Year - a.DateOfBirth.Year,
Song_Count = a.Songs.Count
}).ToList();
dgvArtists.DataSource = xList;
Now my query is giving me an error that says: Cannot implicitly convert type 'System.Collections.Generic.List<final.artistlist>' to 'Final.SortableBindingList<final.artistlists>'
Well... You're doing it wrong. Steps to do:
List<ArtistList> xList = context..
...
.ToList();
BindingList<ArtistList> blArtists = new BindingList<ArtistList>(xList);
SortableBindingList<ArtistList> sblArtists = new SortableBindingList<ArtistList>(bl);
dgvArtists.DataSource = blArtists;
Good luck!