在很久很久以前,DataSet操作是.Net中的一個重要使用手段,其實現在也是 。
在很久很久以前,我的項目操作方式是通過數據Fill一個DataSet,之後返回 給業務層做處理,之後給頁面去顯示。
隨著時間積累,越來越不喜歡DataSet,我記得有人跟我說DataTable比 DataSet效率高,我不反駁也不認同,不知道。
我只知道DataSet如果不做任何處理在WebService上傳輸效率極其低下。
之後的編程模式中引入了對象的概念。至於對象的好處,在此不做論述。
這篇文章主要表述不是對象如何好,而是如何在Winform中DataGridView綁定 對象支持排序功能。
首先,一個測試的實體類。
Code
/// <summary>
/// 用戶信息實體
/// </summary>
public struct UserInfo
{
private string id;
public string Id
{
get { return id; }
set { id = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private string password;
public string Password
{
get { return password; }
set { password = value; }
}
private string email;
public string Email
{
get { return email; }
set { email = value; }
}
private string address;
public string Address
{
get { return address; }
set { address = value; }
}
}
之後做綁定處理
Code
BindingList<UserInfo> infos = new BindingList<UserInfo>(); UserInfo myUserInfo = new UserInfo(); myUserInfo.Id = "1"; myUserInfo.Name = "張三"; myUserInfo.Password = "111111"; myUserInfo.Email = "aa@bb.com"; myUserInfo.Address = "浙江寧波"; infos.Add(myUserInfo); UserInfo myUserInfo1 = new UserInfo(); myUserInfo1.Id = "2"; myUserInfo1.Name = "李四"; myUserInfo1.Password = "123456"; myUserInfo1.Email = "cc@bb.com"; myUserInfo1.Address = "上海"; infos.Add(myUserInfo1); this.dataGridView1.DataSource = infos;
這是最常用的一種用對象綁定數據源的手段。
當然也可以使用BindingSource組件,BindingSource 組件的本質是生成一個 BindingList<UserInfo>的列表。
這樣做會產生一個結果就是,如果使用的數據源是DataSet,則可以點擊標題 進行字段排序,但是如果使用List<T>或者BindingList<T>的集合類 就不能實現。
處理手段
做排序處理,做本質的辦法是繼承ICompare接口,重新Compare方法。
新建一排序類
通過PropertyDescriptor和ListSortDirection完成對象屬性排序功能。
Code
class ObjectPropertyCompare<T> : System.Collections.Generic.IComparer<T>
Code
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;
}
else
{
return returnValue * -1;
}
}
之後處理BindingList<T>
Code
public class BindingCollection<T> : BindingList<T>
重寫BindingList<T>的兩個方法。
ApplySortCore,RemoveSortCore
BindingList<T>繼承於Collection<T>繼承於IList<T>。
Code
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;
}
else
{
isSorted = false;
}
sortProperty = property;
sortDirection = direction;
this.OnListChanged(new ListChangedEventArgs
(ListChangedType.Reset, -1));
}
本文配套源碼