我正在对绑定到通用列表的gridview进行自定义排序。
我的问题如下:
If direction.ToLower.Contains("desc") Then
mygv.DataSource = myList.OrderByDescending(Function(w) w.Name)
GridViewSortDirection = SortDirection.Descending
Else
mygv.DataSource = myList.OrderBy(Function(w) w.Name)
GridViewSortDirection = SortDirection.Ascending
End If
mygv.DataBind()
如何将字段w.Name
替换为此函数的参数,因为它可能是名称,城市,国家或任何其他字段?
P.S。在C#中使用匿名类型很容易,但我在这里使用vb.net。
谢谢
答案 0 :(得分:0)
假设您正在尝试执行此操作,因为您正在使用Linq to EF或Linq to SQL ...
Import System.Linq.Expressions
Dim propertyName = "Name"
If direction.ToLower.Contains("desc") Then
mygv.DataSource = myList.OrderByDescending(PropertyOf(Of Row)(propertyName))
GridViewSortDirection = SortDirection.Descending
Else
mygv.DataSource = myList.OrderBy(PropertyOf(Of Row)(propertyName))
GridViewSortDirection = SortDirection.Ascending
End If
mygv.DataBind()
Public Function PropertyOf(Of T)(string propertyName) as Expression(Of Func(Of T, object))
Dim param = Expression.Parameter("x", typeOf T)
Dim property = Expression.PropertyOrField(param, propertyName);
Return Expression.Lambda(property, param)
End Function
答案 1 :(得分:0)
在gridview的以下事件中添加此代码:
Protected Sub Gridview_Sorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs) Handles Gridview.Sorting
myList = myList.OrderBy(Function(x) x.GetType().GetProperty(e.SortExpression).GetValue(x)).ToList()
End Sub
这应该可以胜任。