我在使用自定义实体类
排序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>
现在在排序中,它在排序Subscription的Native属性
时工作正常 <asp:TemplateField HeaderText="Subscription ID" SortExpression="SubscriptionID">
但是我在排序所包含的类(Customer)
的属性方面遇到了问题 <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;
}
}
请提前告知
答案 0 :(得分:0)
您可以尝试的一个快速而肮脏的事情是将CustomerName属性添加到Subscription类。我通常在使用Silverlight / WCF / EF时在客户端代码分部类中执行此操作。
public string CustomerName
{ get
{ return Customer != null ? Customer.CustomerName : string.empty }
}
然后从您的UI中引用此属性。