我的首選是使用一箇中間[observable]集合,它保存排序的實體。然而,這是在WPF/MVVM世界。即使如此,對於使用集合的ASP.NET ObjectDataSource或MVC,模式仍然相同。這已經有一段時間了,但也許我可以大腦轉儲一下,希望你能找到有用的東西。
我從記憶中拉出這樣的記憶,這不過是爲了幫助你指出某個方向。
我們將使用的表單變量。
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
我知道這是不是一個確切的答案,但因爲沒有人會附和,也許你可以利用這個,砍它,直到它工作正常然後爲下一個人評論你的解決方案。