使用PagedDataSource给Repeater、DataList增加分页

Repeater和DataList是数据库中常用的数据显示控件,它们和DataGrid相比较因为没有分页等复杂的功能,因此性能高,同时Repeater自定义模板又给我们带来了很大的灵活性。但是Repeater和DataList没有分页功能,有时很不方便。目前有很多增加分页的方法,包括使用存储过程来控制每页的数据读取,这些分页制作起来都很麻烦,下面介绍一种使用PagedDataSource给Repeater、DataList增加分页的方法。

PagedDataSource类封装了DataGrid控件的属性,从而使DataGrid控件可以执行分页,它就是一个数据的容器,我们先把数据从数据库中读取出来放在这个容器中,然后设置容器的属性取出当前要显示的页上的部分数据,然后将此部分数据再绑定到页面上的显示控件上。我们同样可以将它用在Repeater和DataList中,下面给出一个实例帮助大家理解如何使用PagedDataSource类。
页面显示元素如下:

后台代码如下:

 1Private Sub Page_Load(ByVal sender As System.ObjectByVal e As System.EventArgs) Handles MyBase.Load
 2        '建立数据库连接,获取数据
 3        Dim sqlconn As New SqlConnection(ConfigurationSettings.AppSettings.Get("sqlserver"))
 4        sqlconn.Open()
 5        Dim sqlda As New SqlDataAdapter("select * from vote_items", sqlconn)
 6        Dim dt As New DataTable
 7        sqlda.Fill(dt)
 8        sqlda.Dispose()
 9
10        '将数据设置为PagedDataSource的数据源,并设置相关参数
11        Dim pds As New PagedDataSource
12        '注意和其它控件DataSource不同的是,这里不能直接写dt,因为PagedDataSource.DataSource实现了IEnumerable
13        '接口,而DataTable没有实现此接口,只有DataView实现了此接口
14        pds.DataSource = dt.DefaultView
15        '==================================================
16        pds.AllowPaging = True
17        pds.PageSize = 3 '每页显示的项目数
18
19        '从URL参数中获取page页码参数
20        Dim currentpage As Integer
21        If Request.QueryString.Get("page"<> Nothing Then
22            currentpage = Convert.ToInt32(Request.QueryString("Page"))
23        Else
24            currentpage = 1
25        End If
26        '设置当前要显示的数据页
27        pds.CurrentPageIndex = currentpage - 1
28
29        Label1.Text = "共有记录" & pds.DataSourceCount & "条,分" & pds.PageCount & "页显示,每页显示" & _
30        pds.PageSize & "条,当前为第" & currentpage & "页:"
31
32        '根据首页和尾页控制链接的显示
33        If Not pds.IsFirstPage Then
34            lnkPrev.NavigateUrl = Request.CurrentExecutionFilePath & "?Page=" & Convert.ToInt32(currentpage - 1)
35            lnkFirst.NavigateUrl = Request.CurrentExecutionFilePath & "?Page=1"
36        End If
37
38        If Not pds.IsLastPage Then
39            lnkNext.NavigateUrl = Request.CurrentExecutionFilePath & "?Page=" & Convert.ToInt32(currentpage + 1)
40            lnkLast.NavigateUrl = Request.CurrentExecutionFilePath & "?Page=" & pds.PageCount
41        End If
42
43        '将PagedDataSource绑定到Repeater
44        rp.DataSource = pds
45        rp.DataBind()
46    End Sub

事实上,功能还有很多可以改进的地方,例如将使用链接控制页数换成使用按钮来控制,这里就不多说了,大家可以自己研究一下。

posted @ 2007-01-18 09:44  Jailu  阅读(1718)  评论(1编辑  收藏  举报