Get the total count of pages. | Get the real page number. | Using Skip and Take to Page | The Actual Paging Controls
So in part one I posted the method to find the total count of pages you’ll need so that you don’t go too far while paging. Now it’s about trying to get the best possible page number despite what’s passed in.
Here’s the situation, when you are paging up or down, you want to make sure you don’t go lower than 0 or higher than whatever the total count of pages is. Sometimes though, things go wrong. They go very wrong. It’s possible that your ui design will allow for any number to be passed in as the page number (Too many reasons this could happen to bother with). Say you have only 10 possible pages but the number 12 gets passed in. Well you either allow it to grab a non existant page 12 or you have a method to determine the best possible choice at this point (10). Turns out it’s idiot simple… what? Were you expecting anything different?
public static Int32 GetRealPage(Int32 totalCountOfPages, Int32 pageNumber) { //pageNumber and totalCountOfPages have to be above 0 or problems if (pageNumber > 0 && totalCountOfPages > 0) { //If page number is higher than the possible count of pages, //then you just need the total count to be the new page number... //but there's one more step pageNumber = totalCountOfPages < pageNumber ? totalCountOfPages : pageNumber; //If by chance the pageNumber now is the same as totalCountOfPages //(Meaning it was larger than totalCountOfPages originally) //1 has to be subtracted to make sure it's inline with a 0 based system where //page 1 is actually 0. This will make more sense when using skip and take in //the next post. pageNumber = totalCountOfPages != pageNumber ? pageNumber : totalCountOfPages - 1; } else { pageNumber = 0; } return pageNumber; }
Ok so I’m going to claim this is amazing stuff, but it will come in handy with the next post.