天天看点

Winform中DataGridView绑定IList数据源后的排序

首先,实现ICompare接口

public class ObjectPropertyCompare<T> : IComparer<T> {

private PropertyDescriptor property;

private ListSortDirection direction;

// 构造函数

public ObjectPropertyCompare(PropertyDescriptor property, ListSortDirection direction) {

this.property = property;

this.direction = direction;

}

// 实现IComparer中方法

public int Compare(T x, T y) {

object xValue = x.GetType().GetProperty(property.Name).GetValue(x, null);

object yValue = y.GetType().GetProperty(property.Name).GetValue(y, null);

int returnValue;

if (xValue is IComparable) {

returnValue = ((IComparable)xValue).CompareTo(yValue);

} else if (xValue.Equals(yValue)) {

returnValue = 0;

} else {

returnValue = xValue.ToString().CompareTo(yValue.ToString());

if (direction == ListSortDirection.Ascending) {

return returnValue;

return returnValue * -1;

然后创建自定义的类,实现IBindingList接口,为方便起见,这里直接继承BindingList类

/// <summary>

/// 自定义绑定列表类

/// </summary>

/// <typeparam name="T">列表对象类型</typeparam>

public class BindingCollection<T> : BindingList<T> {

private bool isSorted;

private PropertyDescriptor sortProperty;

private ListSortDirection sortDirection;

/// 构造函数

public BindingCollection()

: base() {

/// <param name="list">IList类型的列表对象</param>

public BindingCollection(IList<T> list)

: base(list) {

/// 自定义排序操作

/// <param name="property"></param>

/// <param name="direction"></param>

protected override void ApplySortCore(PropertyDescriptor property, ListSortDirection direction) {

List<T> items = this.Items as List<T>;

if (items != null) {

ObjectPropertyCompare<T> pc = new ObjectPropertyCompare<T>(property, direction);

items.Sort(pc);

isSorted = true;

isSorted = false;

sortProperty = property;

sortDirection = direction;

this.OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));

/// 获取一个值,指示列表是否已排序

protected override bool IsSortedCore {

get {

return isSorted;

/// 获取一个值,指示列表是否支持排序

protected override bool SupportsSortingCore {

return true;

/// 获取一个只,指定类别排序方向

protected override ListSortDirection SortDirectionCore {

return sortDirection;

/// 获取排序属性说明符

protected override PropertyDescriptor SortPropertyCore {

return sortProperty;

/// 移除默认实现的排序

protected override void RemoveSortCore() {

创建BindingCollection后即可直接应用:

原来的方式是:

IList<object> list = new List<object>();

...

dataGridView.DataSource = list;

现在只需更改最后一句为:

dataGridView.DataSource = new BindingCollection<object>(list);

即可