Blog

Gallery Control - How to Paginate Data

Here's the best sample app that shows how to page and add previous and next buttons to a gallery.

If you need to need to add paging functionality to a gallery control,hpkeong's post here provides a fantastic guide.

Here, hpkeong describes how to add a gallery control that includes first, last, previous, and next buttons. You can download the example app through his forum post, and here's a screenshot of the sample app.


This is an excellent app that demonstrates many useful techniques, including searching (by record number and page number), and also labels to show the total records count, page number, and total page numbers. Here's a very brief summary of how this app works.

The first part of hpkeong's code calculates the number of records that each page displays by dividing the gallery height by the gallery template height. This technique is very clever because it saves us from to hard-coding the number of records per page, and enables us to resize our gallery control at a later point in time without us having to change any of our formulas.

To populate the data for any given page, the syntax of the Gallery control's Item property looks like this:

LastN(FirstN(DataSource, TotalRecordCountForCurrentPage), NumberOfRowsPerPage)

TotalRecordCountForCurrentPage is a numeric variable equal to this:

Current page number * Number of rows per page

The LastN/FirstN syntax displays the last batch of records for TotalRecordCountForCurrentPage, which equates to the batch of records that corresponds to the current page number.

The formula for the 'next page button' increments the TotalRecordCountForCurrentPage variable by the NumberOfRowsPerPage.

UpdateContext({TotalRecordCountForCurrentPage:TotalRecordCountForCurrentPage + NumberOfRowsPerPage}))

Conversely, the 'previous page button' decrements the TotalRecordCountForCurrentPage variable by the NumberOfRowsPerPage.

UpdateContext({TotalRecordCountForCurrentPage:TotalRecordCountForCurrentPage + NumberOfRowsPerPage}))
In hpkeong's full example, he includes all the additional checks to make sure that the previous/next buttons don't work if you're on the first/last page respectively.

The 'first button' displays the first set of records by setting TotalRecordCountForCurrentPage to the NumberOfRowsPerPage.

UpdateContext({TotalRecordCountForCurrentPage:NumberOfRowsPerPage}))

The 'last button' displays the last batch by setting TotalRecordCountForCurrentPage to the total row count of the record source.

UpdateContext({TotalRecordCountForCurrentPage:CountRows(DataSource)}))
This is just the brief overview of how this works, and I recommend that you visit the forum post to see the full details. Well done PK!