Fox
Fox

Reputation: 891

Which page is my record going to be on?

Interesting and I think a bit of a tricky one, but hey, I'm sure someone out there has faced and found a fix for the issue.

Anyways, the requirement is simple enough, but the solution not.

I'm using a standard ASP.Net Listview control with EF datasource. I have loads of records in my listview and thus use a Asp.Net Pager. I've placed a textbox on my page with a search button and I want to be able to jump to the page where the record specified in the search box is on. The record in my case is a property in my EF Modal. Below the code i'm using on my page

protected void JumptoRecordPostToServer_Click(object sender, EventArgs e)
{
    int pagenrofjumptorecord = InspectionsBusinessObject.GetPageNumberforJumptoRecord(currentusername.Value, pid, DataPager1.PageSize, recordtoFind, Common.Util.GetUserRole());
    this.Response.Redirect(string.Format("/foo.aspx?SelectedPage=", pagenrofjumptorecord.ToString()));            
}

The GetPageNumberforJumptoRecord Method has a couple of parameters not really relevant to this question , but here is the code for that method

public static int GetPageNumberforJumptoRecord(string UserName,Guid ProjectID,int ItemsPerPage,int SiteNumber,UserRoles CurrentRole)
{
    using (MyEFEntity context = new MyEFEntity())
    {
        try
        {
            //allsites = integer
            int[] allsites = context.INSPECTIONS.Where(z => z.ProjectID.Equals(ProjectID)).Select(z => z.HouseSiteNo).ToArray();

            Array.Sort(allsites);                

            int sitetoSearchforIndex = Array.IndexOf(allsites, SiteNumber);

            int totalNrofItems = allsites.Length;

            if (sitetoSearchforIndex != -1)
            {
                int nrofPages = totalNrofItems / ItemsPerPage; // <------- I guess my alghorithm here is wrong
                return (sitetoSearchforIndex * nrofPages) / totalNrofItems; // <------- I guess my alghorithm here is wrong
            }
        }
        catch {}
        return -1;
    }
}

Upvotes: 0

Views: 104

Answers (1)

mafue
mafue

Reputation: 1878

I don't think you need to calculate the total number of pages (nrofPages), this should be enough:

int selectedPage = GetPage(sitetoSearchforIndex, ItemsPerPage, false);

public int GetPage(int indexOfItem, int itemsPerPage, bool startAtPageZero)
{
    int selectedPage = indexOfItem / itemsPerPage;      
    return startAtPageZero ? selectedPage : ++selectedPage;
}

Tests:

bool sapz = false; // pages start at 1
GetPage(0, 10, sapz).Dump();   // 1st item - Page 1
GetPage(9, 10, sapz).Dump();   // 10th     - Page 1
GetPage(10, 10, sapz).Dump();  // 11th     - Page 2
GetPage(14, 10, sapz).Dump();  // 15th     - Page 2
GetPage(99, 10, sapz).Dump();  // 100th    - Page 10
GetPage(100, 10, sapz).Dump(); // 101st    - Page 11

Upvotes: 0

Related Questions