Sort Column data in GridView with Entity Framework
Using db As New Model.ApplicationEntities()
Dim q = From tm In db.lk_xyzEnitty
.... .... .. .....
Select ..... ...... ..
' Logic to sort the resultant list based on sort expression
If Not ResourceSortExpression Is Nothing AndAlso ResourceSortExpression <> String.Empty Then
' From grid, if click on sort link then below logic applied
Dim param = Expression.Parameter(GetType(lk_xyzEnitty), CStr(ResourceSortExpression))
Dim sortExpression = Expression.Lambda(Of Func(Of lk_xyzEnitty, Object))(Expression.Convert(Expression.Property(param, ResourceSortExpression), GetType(Object)), param)
If ResourceSortDirection = "ASC" Then
gridViewControl.DataSource = q.ToList().AsQueryable().OrderBy(sortExpression)
Else
gridViewControl.DataSource = q.ToList().AsQueryable().OrderByDescending(sortExpression)
End If
Else
' By default or First time, resources order by Name
gridViewControl.DataSource = q.ToList()
End If
gridViewControl.DataBind()
End Using
Note: ResourceSortExpression is property.
ResourceSortExpression = e.SortExpression from gridViewControl_Sorting event handler.
Dim q = From tm In db.lk_xyzEnitty
.... .... .. .....
Select ..... ...... ..
' Logic to sort the resultant list based on sort expression
If Not ResourceSortExpression Is Nothing AndAlso ResourceSortExpression <> String.Empty Then
' From grid, if click on sort link then below logic applied
Dim param = Expression.Parameter(GetType(lk_xyzEnitty), CStr(ResourceSortExpression))
Dim sortExpression = Expression.Lambda(Of Func(Of lk_xyzEnitty, Object))(Expression.Convert(Expression.Property(param, ResourceSortExpression), GetType(Object)), param)
If ResourceSortDirection = "ASC" Then
gridViewControl.DataSource = q.ToList().AsQueryable().OrderBy(sortExpression)
Else
gridViewControl.DataSource = q.ToList().AsQueryable().OrderByDescending(sortExpression)
End If
Else
' By default or First time, resources order by Name
gridViewControl.DataSource = q.ToList()
End If
gridViewControl.DataBind()
End Using
Note: ResourceSortExpression is property.
ResourceSortExpression = e.SortExpression from gridViewControl_Sorting event handler.
Comments