Alert Working with Data in ASP.NET 2.0 tutorial reader Nathan P. wrote in to let me know that there is a small bug in the code for the paging and sorting with the DataList and Repeater tutorials. It's a silly off-by-one error that I should have caught long before turning in the tutorials.
In any event, the problem in the default paging examples is in computing the PageCount. I use:
1 private int PageCount
2 {
3 get
4 {
5 return (TotalRowCount / PageSize) + 1;
6 }
7 }
Which works well unless TotalRowCount and PageSize are evenly divisible. For example, let TotalRowCount = 79 and PageSize = 10, then this formula works as desired since 79/10 = 7, and 7+1 = 8, indicating that there are, indeed, 8 pages. But if there are 80 records in total, then 80/10 = 8, and 8+1 = 9, even though there are just 8 pages of data.
I fixed this by changing this to the following:
1 private int PageCount
2 {
3 get
4 {
5 if (TotalRowCount <= 0 || PageSize <= 0)
6 return 1;
7 else
8 return ((TotalRowCount + PageSize) - 1) / PageSize;
9 }
10 }
Alternatively, you could just return ((TotalCount - 1) / PageSize) + 1, which is equivalent to the formula in on line 8 in the above snippet.
Similarly, in the custom paging example I have the same off-by-one error, but it's in computing the starting index of the last page. In the ProductsDataSource's Selecting event handler there is:
int
LastPageStartRowIndex = (TotalRowCount / MaximumRows) * MaximumRows;
Change this to:
int
LastPageStartRowIndex = ((TotalRowCount - 1) / MaximumRows) * MaximumRows;
Also update this formula in the LastPage Button's Click event handler.
I've submitted the code/article updates for the affected tutorials. It should be updated on the live site within a few days, hopefully.