0

I am trying to create a pagination for a website. However, whenever I click the button that signals the server to go to the next page, it will still load the same page (e.g. from page 1 to page 2), but it then works correctly from page 2 onwards displaying an incorrect page number in the page label (e.g. pagelabel = 3, currentpage=2). There is also the issue of not reaching the last page since the page does not seem to start at page 1, but when I proceed to click the page_back_button, it will then proceed to display the last page. I am having troubles in finding the source of this problem. Here is the source code that I created.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        LoadPageSizer();
        LeadStatusDDL();
        Session["curr_page"] = 1;
    }

    rptLeadsPager.DataSource = ListLeads(ddlLStatus.Text.ToString(), Convert.ToInt16(Session["curr_page"]), Convert.ToInt16(ddlPageSize.Text));
    rptLeadsPager.DataBind();

    BuildPagination(Convert.ToInt16(Session["total_page"]), Convert.ToInt16(Session["curr_page"]), 10);
}

#region DDL List for Results/Page
private void LoadPageSizer()
{
    ddlPageSize.Items.Add("10");
    ddlPageSize.Items.Add("15");
    ddlPageSize.Items.Add("20");
    ddlPageSize.Items.Add("25");
    ddlPageSize.Items.Add("30");
    ddlPageSize.Items.Add("40");
    ddlPageSize.Items.Add("50");
}
#endregion

#region DDL List for LeadsStatus
private void LeadStatusDDL()
{
    ddlLStatus.Items.Add(new ListItem("Not Qualified"));
    ddlLStatus.Items.Add(new ListItem("Qualified"));
}
#endregion

#region SQL Stored Procedure
private DataTable ListLeads(string leadStatus, int pageNumber, int pageSize)
{
    int searchResultsCount;
    DataSet dsSearchResults;

    using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.AppSettings["sqlConnection"]))
    {
        using (var sqlCommand = new SqlCommand("LeadsPager", sqlConnection))
        {
            sqlCommand.CommandType = CommandType.StoredProcedure;

            //add parameters
            sqlCommand.Parameters.AddWithValue("@LeadsStatus", leadStatus);
            sqlCommand.Parameters.AddWithValue("@PageNumber", pageNumber);
            sqlCommand.Parameters.AddWithValue("@ResultsPerPage", pageSize);

            var resultsCountParam = new SqlParameter("@SearchResultsCount", SqlDbType.Int);
            resultsCountParam.Direction = ParameterDirection.Output;
            sqlCommand.Parameters.Add(resultsCountParam);

            using (var sqlDataAdapter = new SqlDataAdapter(sqlCommand))
            {
                dsSearchResults = new DataSet();
                sqlDataAdapter.Fill(dsSearchResults);

                searchResultsCount = int.Parse(resultsCountParam.Value.ToString());
            }
        }
    }

    if (searchResultsCount == 0)
    {
        ResultHeader.Visible = false;
        ResultFooter.Visible = false;
    }
    else
    {
        Session["total_page"] = GetTotalPage(pageSize, searchResultsCount);
        lblTotalPage.Text = Session["total_page"].ToString();
        ResultHeader.Visible = true;
        ResultFooter.Visible = true;
    }

    RenderToolbar();

    if (dsSearchResults.Tables.Count > 0)
        return dsSearchResults.Tables[0];
    else
        return null;
}
#endregion

#region Header Function
private void RenderToolbar()
{
    int intCurPage = Session["curr_page"] == null ? 1 : Convert.ToInt16(Session["curr_page"]);
    int intTotalPage = Session["total_page"] == null ? 1 : Convert.ToInt16(Session["total_page"]);
    btnUpPageBack.Visible = intCurPage > 1;
    btnUpPageNext.Visible = intTotalPage > intCurPage;
    lblPage.Text = Session["curr_page"] == null ? "1" : Session["curr_page"].ToString();
}
#endregion


#region Pagination
protected void BuildPagination(int PageCount, int CurrentPageIndex, int ButtonsCount)
{
    pnlPager.Controls.Clear(); //

    if (PageCount <= 1) return; // at least two pages should be there to show the pagination

    //finding the first linkbutton to be shown in the current display
    int start = CurrentPageIndex - (CurrentPageIndex % ButtonsCount);

    //finding the last linkbutton to be shown in the current display
    int end = CurrentPageIndex + (ButtonsCount - (CurrentPageIndex % ButtonsCount));

    //if the start button is more than the number of buttons. If the start button is 11 we have to show the <<First link
    if (start > ButtonsCount - 1)
    {
        pnlPager.Controls.Add(createButton("&lt;&lt;", 0));
        pnlPager.Controls.Add(createButton("..", start - 1));
    }

    int i = 0, j = 0;

    for (i = start; i < end; i++)
    {
        //LinkButton lnk;
        if (i < PageCount)
        {
            if (i + 1 == CurrentPageIndex) //if its the current page
            {
                Label lbl = new Label();
                lbl.Text = (i + 1).ToString();
                pnlPager.Controls.Add(lbl);
            }
            else
            {
                pnlPager.Controls.Add(createButton((i+1).ToString(), i));
            }
        }
        j++;
    }

    //If the total number of pages are greaer than the end page we have to show Last>> link
    if (PageCount > end)
    {
        pnlPager.Controls.Add(createButton("..", i));
        pnlPager.Controls.Add(createButton("&gt;&gt;", PageCount - 1));
    }
}

private LinkButton createButton(string title, int index)
{
    LinkButton lnk = new LinkButton();
    lnk.ID = "btnPage" + title + "_" + index.ToString();
    lnk.Text = title;
    lnk.CommandArgument = index.ToString();
    lnk.Click += new EventHandler(lnkPager_Click);
    return lnk;
}

#endregion Pagination

#region Get Total Page Function
private static string GetTotalPage(int vPageDisplay, int vTotalData)
{
    decimal dlQuot = decimal.Divide(vTotalData, vPageDisplay);
    int dlPresQuot = vTotalData / vPageDisplay;
    return (dlQuot > dlPresQuot ? dlPresQuot + 1 : dlPresQuot).ToString();
}
#endregion


#region Navigating Page with Buttons Function
protected void NextPage_Click(object sender, EventArgs e)
{
    Session["curr_page"] = Convert.ToInt16(Session["curr_page"]) + 1;
    //Converts Results/Page to INT
    ListLeads(ddlLStatus.Text.ToString(), Convert.ToInt16(Session["curr_page"]), Convert.ToInt16(ddlPageSize.Text));
}

protected void BackPage_Click(object sender, EventArgs e)
{
    Session["curr_page"] = Convert.ToInt16(Session["curr_page"]) - 1;
    ListLeads(ddlLStatus.Text.ToString(), Convert.ToInt16(Session["curr_page"]), Convert.ToInt16(ddlPageSize.Text));
}

protected void lnkPager_Click(object sender, EventArgs e) //Page index changed function
{
    LinkButton lnk = (LinkButton)sender;
    Session["curr_page"] = int.Parse(lnk.CommandArgument) + 1;
    ListLeads(ddlLStatus.Text.ToString(), Convert.ToInt16(Session["curr_page"]), Convert.ToInt16(ddlPageSize.Text));
}
#endregion

UPDATE! I have fixed the problem of the link buttons.

However, there is a new problem. Whenever I am in a specific page (ex. Page Number 6) and I select from the Results Per Page Drop-Down List (ex. From 20 to 50) the total page would then change from (ex. 9 to 3).

However! The specific page that I am currently on (Page 6) is out of bounds of the Total Page (ex. total page = 3, my current page = 6). It will then display nothing and I have to click the button backwards just to reach the last page of the new Results Per Page list.

I have created a code to specify where the Session["curr_page"] should be whenever this happens. However, I could not determine where to put this code, since it does not fire whenever I change the results per page drop down list. Here is the code that I made.

if (Convert.ToInt16(Session["curr_page"]) > Convert.ToInt16(Session["total_page"]))
{
    Session["curr_page"] = Session["total_page"];
}
4

2 回答 2

2

The problem is you are not rebinding your data. The first time they hit your page, Session["curr_page"] = 1;, you build and set your data source, and then bind it. When the user clicks the Next button, the page reloads and on Page_Load, Session["curr_page"] still equals 1, you build and set your data source, and then bind it (so, same results as initial page load).

Then NextPage_Click executes, you increment Session["curr_page"], and rebuild your datasource... but you never set and bind it.

So you could do something like:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadPageSizer();
            LeadStatusDDL();
            Session["curr_page"] = 1;
            BindAndPage();
        }
    }

    private void BindAndPage()
    {
        rptLeadsPager.DataSource = ListLeads(ddlLStatus.Text.ToString(), Convert.ToInt16(Session["curr_page"]), Convert.ToInt16(ddlPageSize.Text));
        rptLeadsPager.DataBind();

        BuildPagination(Convert.ToInt16(Session["total_page"]), Convert.ToInt16(Session["curr_page"]), 10);
    }

    //other code

    protected void NextPage_Click(object sender, EventArgs e)
    {
        Session["curr_page"] = Convert.ToInt16(Session["curr_page"]) + 1;
        BindAndPage();
    }
于 2013-02-08T14:23:50.993 回答
1

You can use "DataTable" javascript functionality for this problem. Please refer https://www.datatables.net/.

$(document).ready(function(){
    $('#myTable').DataTable();
});

only set your table id here and it will automatically set pagination, sorting, filtering of your table.

Thanks

于 2016-05-03T11:12:42.287 回答