我正在对绑定到泛型列表的网格视图进行自定义排序。
我的问题如下:
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
替换为此函数的参数,因为它可能是名称、城市、国家或任何其他字段?
附言在C#中使用匿名类型很容易,但我在这里使用 vb.net。
谢谢
假设您正在尝试执行此操作,因为您使用的是 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
在网格视图的以下事件中添加此代码:
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
这应该可以完成这项工作。