如何在列标题单击的DataGridView中对DataBound列进行排序?

时间:2011-06-03 14:26:43

标签: c# .net datagridview

我相信这应该自动处理。我将DataGridView绑定到一个对象数组:

public class Entity {    
    public string Name { get; set; }     
    public int PrimaryKey { get; set; }
}

绑定网格:

public void BindGrid(Entity[] entities) {
    grdEntities.DataSource = entities;
}

当我单击“名称”列中的列标题时,即使SortMode设置为自动,也不会发生任何事情。列标题中也缺少排序字形。

我尝试绑定IBindingListIList,但这不起作用。

我希望有一个简单,优雅的解决方案,可以在DataGridViewDataGridViewColumn上设置属性,而不必创建一个新类来支持排序。通过单击DataBound DataGridView上的标题,我应该如何支持对列进行排序?

2 个答案:

答案 0 :(得分:5)

我创建了一个新的基于IComparer的界面,允许您指定列和方向。我只是这样做是因为我需要我的排序代码尽可能通用 - 我有两个网格需要像这样排序,我不想保持两倍的代码。这是界面,非常简单:

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

显然,如果你不担心保持通用(你可能应该),那么这并不是绝对必要的。然后,我构建了一个基于BindingList<>的新类。这允许我覆盖排序代码并逐列提供我自己的IByColumnComparer,这是我所需要的灵活性。看看这个:

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;
  }
}

编辑这应该提供一些有关如何根据上面的界面创建自己的IComparer的信息。 基于接口拥有自己的IComparer的好处是你可以单向排序某些列,而另一列排序(某些列可能是字符串,有些是int,有些列可能有关于最重要的列的特殊规则,等)的。以下是IComparer如何工作的示例:

public class MyGenericComparer : IByColumnComparer
{
  private string columnToCompare;
  private bool descending;

  public string SortColumn
  {
     get { return columnToCompare; }
     set { columnToCompare = value; }
  }

  public bool SortDescending
  {
     get { return descending; }
     set { descending = value; }
  }

  public MyGenericComparer(string column, bool descend)
  {
     columnToCompare = column;
     descending = descend;
  }

  public int Compare(object x, object y)
  {
     MyGenericObject firstObj = (MyGenericObject )x;
     MyGenericObject secondObj = (MyGenericObject )y;

     if (descending) 
     {
        MyGenericObject tmp = secondObj ;
        secondObj = firstObj ;
        firstObj = tmp;
     }

     if (columnToCompare == "StringColumn")
     {
        //Run code to compare strings, return the appropriate int
        //eg, "1" if firstObj was greater, "-1" is secondObj, "0" if equal
     }

     if (columnToCompare == "IntColumn")
     {
        //Run code to compare ints, return the appropriate int
        //eg, "1" if firstObj was greater, "-1" is secondObj, "0" if equal
     }
  }
}

然后你要做的就是用比较器的实例创建你的列表!

public static MyGenericComparer GridComparer = new MyGenericComparer();
public static SortableGenericCollection<GenericObject> GridList = new SortableGenericCollection<GenericObject>(GridComparer);

答案 1 :(得分:1)

可能想看看这个问题:DataGridView sort and e.g. BindingList<T> in .NET

基本的想法是,您必须扩展BindingList<T>并覆盖ApplySortCore才能使列排序有效。