我有問題,使用我的自定義實體類排序我的GridView使用自定義實體的數據綁定
我複雜的實體排序問題
public class Subscription
{
public string SubscriptionID { get; set; }
public string Status { get; set; }
public Customer { get; set; } //Contained class from another entity
}
public class Customer
{
public string CustomerID { get; set; }
public CustomerName { get; set; }
}
結合的GridView
List<Subscription> subscriptions = GetSubscriptions();
//sorting, sortEvent is the GridviewSortEvenArgs param
subscriptions.Sort(new GenericComparer<Subscription>(sortEvent.SortExpression, GridViewSortDirection));
grdSubscription.DataSource = subscriptions;
grdSubscription.DataBind();
我用模板字段綁定我的實體字段到電網
<asp:TemplateField HeaderText="Subscription ID" SortExpression="SubscriptionID">
<ItemTemplate>
<%# Eval(" SubscriptionID ") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Customer Name" SortExpression="CustomerName">
<ItemTemplate>
<%# Eval(" Customer.CustomerName ") %>
</ItemTemplate>
</asp:TemplateField>
現在排序,其工作正常排序時認購的原生屬性
<asp:TemplateField HeaderText="Subscription ID" SortExpression="SubscriptionID">
但我有在排序包含類的屬性(客戶)的問題
<asp:TemplateField HeaderText="Customer Name" SortExpression="CustomerName">
<ItemTemplate>
<%# Eval(" Customer.CustomerName ") %>
</ItemTemplate>
我試過的SortExpression =」 Customer.CustomerName」,但無濟於事
我用這個GenericComparer分揀格
public class GenericComparer<T> : IComparer<T>
{
private SortDirection sortDirection;
public SortDirection SortDirection
{
get { return this.sortDirection; }
set { this.sortDirection = value; }
}
private string sortExpression;
public GenericComparer(string sortExpression, SortDirection sortDirection)
{
this.sortExpression = sortExpression;
this.sortDirection = sortDirection;
}
public int Compare(T x, T y)
{
PropertyInfo propertyInfo = typeof(T).GetProperty(sortExpression);
IComparable obj1 = (IComparable)propertyInfo.GetValue(x, null);
IComparable obj2 = (IComparable)propertyInfo.GetValue(y, null);
if (SortDirection == SortDirection.Ascending)
{
return obj1.CompareTo(obj2);
}
else return obj2.CompareTo(obj1);
}
}
個
其他詳細信息:
protected SortDirection GridViewSortDirection
{
get
{
// Checks for the first time when the ViewState sort direction is null
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
// Changes the sort direction
else
{
if (((SortDirection)ViewState["sortDirection"]) == SortDirection.Ascending)
{
ViewState["sortDirection"] = SortDirection.Descending;
}
else
{
ViewState["sortDirection"] = SortDirection.Ascending;
}
}
return (SortDirection)ViewState["sortDirection"];
}
set
{
ViewState["sortDirection"] = value;
}
}
請指教,謝謝提前,你可以嘗試
你是如何結合的排序? – Nix 2011-04-18 13:49:52
請看到我的編輯,感謝 – clydePHI 2011-04-18 13:55:27