我将数据绑定到模板字段中的gridview,例如:
<asp:TemplateField HeaderText="Business Objective" SortExpression="BusinessObjective.BusinessObjectiveText">
<ItemTemplate>
<asp:Label ID="lblBusinessObjectiveText" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "BusinessObjective.BusinessObjectiveText") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
在后面的代码中,我只是将列表绑定到网格视图:
gvBussinessRisks.DataSource = this.BusinessRiskList;
gvBussinessRisks.DataBind();
列表的类型为“BusinessRisk”。实体结构就像
public class BusinessRisk
{
public BusinessRisk()
{
BusinessObjective BusinessObjective = new BusinessObjective();
}
public int? BusinessRiskId { get; set; }
public int ObjectiveId { get; set; }
public string BusinessRiskText { get; set; }
public string Description { get; set; }
public bool IsActive { get; set; }
public long ActionedBy { get; set; }
public long? DelegatedTo { get; set; }
public int? LastLogId { get; set; }
public int AppOwnerId { get; set; }
public BusinessObjective BusinessObjective { get; set; }
}
我的 BusinessObjective 类具有名为“BusinessObjectiveText”的属性,我将其绑定到网格视图中的列之一。
但是当我试图对这个列进行排序时,我得到了错误。
我的排序事件是这样的:
List<BusinessRisk> sortedList = this.BusinessRiskList;
sortedList.Sort(new GenericComparer<BusinessRisk>(e.SortExpression, (SortDirection)Enum.Parse(typeof(SortDirection), GetSortDirection(e.SortExpression))));
gvBussinessRisks.DataSource = sortedList;
gvBussinessRisks.DataBind();
而“GenericComparer”类是:
public class GenericComparer<T> : IComparer<T>
{
private string sortExpression;
private SortDirection sortDirection;
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)
{
if (obj1 != null)
return obj1.CompareTo(obj2);
return 0;
}
else
{
if (obj1 != null)
return obj2.CompareTo(obj1);
return 0;
}
}
public SortDirection SortDirection
{
get { return this.sortDirection; }
set { this.sortDirection = value; }
}
}
当我尝试将此列排序为GenericComparer
类(方法:比较)时,我得到错误,我propertyInfo
得到null
. 如果我使用的属性进行排序,BusinessRisk
那么排序会正确进行,但是在这里我尝试使用 BussinessObjective 类的属性之一进行排序。
我尝试了谷歌,但没有得到任何解决方案。