Search code examples
c#paginationpage-numbering

Displaying page numbers


I'd like to mimic how this paging works:

enter image description here

Notice how the current page will always show two pages on either side? This seems like it would be a lot of conditional code when you factor in the case that you may be on page 4 and there is no gap between 1 and 3 or if you are on page 1 it will show more than two numbers to the right.

Can somebody get me off to the right start?


Solution

  • Here's sample output from console program with logic you are looking for:

    Program.exe 1

    1 2 3...100

    Program.exe 2

    1 2 3 4...100

    Program.exe 5

    1...3 4 5 6 7...100

    using System;
    
    class Program
    {
        static void Main(string[] args)
        {
            // usage program.exe page#
            // page# between 1 and 100
            int minPage = 1;
            int maxPage = 100;
            int currentPage = int.Parse(args[0]);
    
            // output nice pagination
            // always have a group of 5
    
            int minRange = Math.Max(minPage, currentPage-2);
            int maxRange = Math.Min(maxPage, currentPage+2);
    
            if (minRange != minPage)
            {
                Console.Write(minPage);
                Console.Write("...");
            }
    
            for (int i = minRange; i <= maxRange; i++)
            {
                Console.Write(i);
                if (i != maxRange) Console.Write(" ");
            }
    
            if (maxRange != maxPage)
            {
                Console.Write("...");
                Console.Write(maxPage);
            }
        }
    }