[英]Sorting with SortableBindingList and DataGridView [C#]
我正在嘗試解決使用綁定列表對datagridview排序的問題。
我已經實現了SortableBindingList,當用戶單擊datagridview列標題進行排序時,該方法很好用。
但是,我想在加載表單/網格時添加一個“默認”排序,我似乎無法找到解決方法。 我已經看到了這個示例 ,但是它似乎沒有用。
我想要實現的偽代碼:
SortableBindingList<T> TestList = new SortableBindingList<T>();
//Load data to the TestList here
TestList.Sort("Column1", ListSortDirection.Ascending); // Sort by Column 1
gridTest.DataSource = TestList ; // Assign TestList to grid datasource
SortableBindingList:
using System;
using System.Collections.Generic;
using System.ComponentModel;
namespace Lists
{
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;
List<T> list = Items as List<T>;
if (list == null) return;
list.Sort(Compare);
_isSorted = true;
//fire an event that the list has been changed.
OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
}
private int Compare(T lhs, T rhs)
{
var result = OnComparison(lhs, rhs);
//invert if descending
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());
}
}
}
我知道我必須在SortableBindingList類中創建一個公共方法來傳遞列和排序方向。
任何幫助,將不勝感激。
您必須在您的公共方法中獲取PropertyDescriptor
:
public void Sort(string propertyName, ListSortDirection direction)
{
this.ApplySortCore(TypeDescriptor.GetProperties(typeof(T))[propertyName], direction);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.