Friday, November 29, 2013

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)
                    gridViewControl.DataSource = q.ToList().AsQueryable().OrderByDescending(sortExpression)
                End If
                ' By default or First time, resources order by Name
                gridViewControl.DataSource = q.ToList()
            End If


        End Using

NoteResourceSortExpression is property. 
ResourceSortExpression = e.SortExpression from gridViewControl_Sorting event handler.

No comments: