我在模板字段中将数据绑定到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类的属性进行排序。
我试过谷歌,但没有得到任何解决方案。
答案 0 :(得分:1)
最后,在Lot of Google和小小的头脑风暴后,我得到了解决方案,使用Dynamic Linq。
我抛弃了GenericComparer类,只是在Sorting event
中编写了以下代码string sortColumn = e.SortExpression;
IQueryable<BusinessRisk> sortedList = (from p in this.BusinessRiskList
select new BusinessRisk
{
BusinessRiskText = p.BusinessRiskText,
IsActive = p.IsActive,
Description = p.Description,
BusinessObjective = new BusinessObjective { BusinessObjectiveText = p.BusinessObjective.BusinessObjectiveText }
}).AsQueryable().OrderBy(e.SortExpression);
this.BusinessRiskList = sortedList.ToList<BusinessRisk>();
gvBussinessRisks.DataSource = sortedList;
gvBussinessRisks.DataBind();
它的工作对我来说很完美。
谢谢所有试图帮助我的人。