Datalist paging with linq

雨燕双飞 提交于 2020-01-01 11:35:46

问题


I'm creating a page that uses Linqfor data access and I'm using DataList to display data. How can I use Linq to do data paging ? Please read simple code below :

I normally use a PagedDatasource but this only seems to work with a DataTable.

Here's my Linq to return Datatable which is bound with Datalist :

Public Shared Function GetStudentList() As DataTable

    Dim db As New DemoDataClassesDataContext()

    Dim query = From st In db.students _
                Order By st.st_studentid Ascending _
                Select st

    Dim dtStudent = New DataTable("myst")


    dtStudent.Columns.Add("st_id", GetType(Integer))
    dtStudent.Columns.Add("st_userid", GetType(Guid))
    dtStudent.Columns.Add("st_studentid", GetType(Integer))
    dtStudent.Columns.Add("st_firstname", GetType(String))
    dtStudent.Columns.Add("st_lastname", GetType(String))
    dtStudent.Columns.Add("st_gender", GetType(String))
    dtStudent.Columns.Add("st_email", GetType(String))


    For Each q In query
        dtStudent.Rows.Add(New Object() {q.st_id, q.st_userid, q.st_studentid, q.st_firstname, q.st_lastname, q.st_gender, q.st_email})
    Next

    Return dtStudent

End Function

In the code behind of the page :

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    If Not Page.IsPostBack() Then
        LoadData()
    End If

End Sub

Private Sub LoadData()
    dsStduent = da_Student.GetStudentList()
    dt_Student.DataSource = dsStduent
    dt_Student.DataBind()

End Sub

回答1:


You will find the methods .Skip() and .Take() very useful.

I noticed you provided some code from your project, so here's an update on how you should implement these methods.

In your method for getting the data, do the following:

Dim query = (From st In db.students _
            Order By st.st_studentid Ascending _
            Select st).Skip((CurrentPage - 1) * PageSize).Take(PageSize)

Then provide the CurrentPage and PageSize variables as arguments to the method. (You don't want to build them into the data access, as they could vary across different parts of your site...)




回答2:


You need to look at SQL Paging with LINQ using the Skip() and Take() methods.



来源:https://stackoverflow.com/questions/764364/datalist-paging-with-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!