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; //thanks Luca
}
protected override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction)
{
_sortProperty = prop;
_sortDirection = direction;
if (!(Items is List<T> list)) 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; //nulls are equal
}
if (rhsValue == null)
{
return 1; //first has value, second doesn't
}
if (lhsValue is IComparable)
{
return ((IComparable)lhsValue).CompareTo(rhsValue);
}
if (lhsValue.Equals(rhsValue))
{
return 0; //both are the same
}
//not comparable, compare ToString
return lhsValue.ToString().CompareTo(rhsValue.ToString());
}
}
'C# Programming' 카테고리의 다른 글
C# System.ArgumentException : 이 행은 이미 다른 테이블에 속해 있습니다 (0) | 2018.12.18 |
---|---|
C# DataColumn.Expression (0) | 2018.12.18 |
C# 마우스로 폼이동하기 (0) | 2018.12.08 |
C# DataGridView 열 추가된후 열 선택되어있는거 해제하기 (0) | 2018.10.25 |
C# 텔레그렘 봇 (0) | 2018.07.13 |