For whatever reason, I can not figure out how to identify the number of results in a given page. I have a list of data, and a property PageSize which identifies how many results should fit in one page. Let’s say there’s 120 results and the page size is 25. That means there should be a total of 5 pages, the first 4 having 25 records, and the 5th having just 20 records. Right now, the results I’m getting are all over the board, for example I might get 50 when it’s supposed to be 20.
I’m writing this function to return the number of results in a specified page, but I can’t seem to get the simple math right (I was never very good at math). There are no actual lists per page where I can simply read Count to identify the number of records in that page – I need to dynamically calculate it, using this function.
Refer to the line of code just under CALCULATION DONE HERE:
function TMyData.SizeOfPage(const Index: Integer): Integer;
begin
//Index = Page Number (0 ... MAX)
//Result = Number of results in given page
//PageCount = Total number of pages (from other function)
//RecordCount = Total number of records (all pages)
Result:= 0; //Default
//Validate index bounds
if (Index >= 0) and (Index < PageCount) then begin
if Index < PageCount-1 then begin
//Just return full size of one page
Result:= PageSize;
end else begin
//Return number of records in the last page
//--- CALCULATION DONE HERE ---
Result:= RecordCount - Trunc(RecordCount / PageSize);
end;
end else begin
raise Exception.Create('Page index out of bounds ('+IntToStr(Index)+')');
end;
end;
I see no reason to use floating point arithmetic here. I always avoid floating point arithmetic if integer arithmetic suffices.
I would write it like this:
Or perhaps this version:
This is particularly easy to understand. You subtract the records shown on all the full pages, and what is left are the records on the last page.
As far as
PageCountgoes, you can calculate it like so:Thanks to @Rob for his insight.