Thursday, March 29, 2012

Paging with a datarepeater

Adding a paging feature to data displayed in a data repeater is decidedly easy with the simple addition of a paged data source.

I couldn't find much information on this topic in this forum but I did find some decent C# code elsewhere that I translated to VB.Net. Since this forum has helped me more times than I can count I always like to post my solutions in case they some day help someone else.

Use this code in your page load and make sure you have a label called lblCurrentPage above your repeater and two hyperlinks called lnkPrev and lnkNext below your reader. You will also need a data adapter (mine is called sdaData here).

This code handles the rest.

If Not Me.Page.IsPostBack Then
Dim cn As New SqlClient.SqlConnection(Session("PropertyConnection"))
Dim cm As New SqlClient.SqlCommand("", cn)
Dim ds1 As New DataSet
Dim strPsn As String

sdaData.SelectCommand.Connection = cn
sdaData.SelectCommand.CommandText = "select * from [orders] where customer = '" & strWhatever & "' order by orderdate desc"
sdaData.Fill(ds1)

Dim objPds As New PagedDataSource
objPds.DataSource = ds1.Tables(0).DefaultView
objPds.AllowPaging = True
objPds.PageSize = 5 'sets number of pages to display
Dim CurPage As Integer
If Len(Request("Page")) > 0 Then
CurPage = CInt(Request("Page"))
Else
CurPage = 1
End If
objPds.CurrentPageIndex = CurPage - 1
lblCurrentPage.Text = "Page: " & CurPage.ToString() & " of " & objPds.PageCount.ToString()

If Not (objPds.IsFirstPage) Then
lnkPrev.NavigateUrl = "mypage.aspx?page=" & CStr(CurPage - 1)
End If
If Not objPds.IsLastPage Then
lnkNext.NavigateUrl = "mypage.aspx?page=" & CStr(CurPage + 1)
End If

Repeater1.DataSource = objPds
Repeater1.DataBind()
End If

It should be very simple to do the same for a datalist.The best place for this kind of code is the code bank.

0 comments:

Post a Comment