简体   繁体   English

在vb.net中使用通用列表对GridView进行排序

[英]GridView sorting with Generic List in vb.net

I am doing custom sorting on a gridview that is being bound to a generic list. 我在绑定到通用列表的gridview上进行自定义排序。

My problem is the following: 我的问题如下:

    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()

How can I replace the field w.Name with a parameter given to this function since it might be the name, city, country or any other field? 我如何用此函数的参数替换w.Name字段,因为它可能是名称,城市,国家或任何其他字段?

PS in C# using anonymous type it is easy but I am using vb.net here. 使用匿名类型的C#中的PS很容易,但是我在这里使用vb.net。

Thanks 谢谢

Assuming you are trying to do this because you are using Linq to EF or Linq to SQL... 假设您正在尝试执行此操作,因为您使用的是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

Add this code in the following event of the gridview: 在以下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 

This should do the job. 这应该做的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM