У меня проблема с сортировкой моего 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;
}
}
Пожалуйста, сообщите, заранее спасибо