我的偏好是使用包含已排序实体的中间 [observable] 集合。然而,这是在 WPF/MVVM 世界中。即使这样,对于使用集合的 ASP.NET ObjectDataSource 或 MVC,Pattern 仍然相对相同。已经有一段时间了,但也许我可以脑补一下,希望你能找到有用的东西。
我是从记忆中提取出来的,所以记住这只是为了帮助你指明某个方向。
我们将使用的表单变量。
private string SortProperty { get; set; }
private ListSortDirection SortDirection { get; set; }
private ICollection<myItems> items; // Entity Collection
private ObservableCollection<myItems> SortedItems { get; set; } // Sorted Collection
重载表单 OnLoad 事件处理程序以注册标题单击处理程序以应用排序。
protected override void OnLoad(EventArgs e)
{
dataGridView1.ColumnHeaderMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(dataGridView1_ColumnHeaderMouseClick);
LoadDataGridView();
base.OnLoad(e);
}
protected override void OnUnload(EventArgs e)
{
dataGridView1.ColumnHeaderMouseClick -= new System.Windows.Forms.DataGridViewCellMouseEventHandler(dataGridView1_ColumnHeaderMouseClick);
base.OnUnload(e);
}
执行我们对排序数据的初始加载。
private void LoadDataGridView()
{
items = myRepository.GetAllItems(); // However you get or have your collection of items.
ApplySort();
dataGridView1.DataSource = SortedItems;
}
对我们的数据进行排序并保存在新集合中。 OrderBy 需要动态查询库:http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx。
private void ApplySort()
{
// IQueryable<myItems>, ICollection<myItems>, ObservableCollection<myItems>... be aware of cross threading and how you will handle updates.
SortedItems = items.AsQuerable().OrderBy(SortProperty + (SortDirection == ListSortDirection.Ascending ? " asc" : " desc")).ToList();
}
我们的点击事件处理程序。请记住,您必须处理添加、删除和更改的实体。
private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
var propertyName = GetPropertyName(dataGridView1.Columns[e.ColumnIndex])
SortDirection = SortProperty == propertyName ?
SortDirection == ListSortDirection.Ascending ? ListSortDirection.Descending : ListSortDirection.Ascending
: SortDirection;
SortProperty = propertyName;
ApplySort();
dataGridView1.DataSource = SortedItems;
}
简单的排序辅助方法。
private string GetPropertyName(int columnNumber)
{
switch(columnNumber)
{
case 0:
return "Id";
case 1:
return "Name";
default:
return "Id";
}
}
以下是一些附加信息:
http://msdn.microsoft.com/en-us/library/ms171608.aspx
我知道这不是一个确切的答案,但由于没有其他人会加入,也许你可以接受这个,修改它直到它正常工作,然后为下一个人评论你的解决方案。