Search code examples
asp.netgridviewpage-index-changed

After paging GridVIew does not display all data when searched


My GridView does not display correct data after searched performed on its second page.

After populating the GridView and navigating to the second page with PageIndexChanging method, GridView is not refreshed after applying search filters. It remains on the same page but have to be reloaded.

My search invokes the following method:

private void PopulatePeople()
{
    lblAddError.Text = String.Empty;
    if (ViewState["_message"] != null)
    {
        lblAddError.Visible = true;
        lblAddError.Text = ViewState["_message"].ToString();
    }
    ViewState["_message"] = null;

    int portfolio = int.Parse(ddlPortfolio.SelectedItem.Value);
    ViewState["_portfolioID"] = portfolio;
    string year = ddlYear.SelectedItem.Text;
    string month = ddlMonth.SelectedItem.Text;

    if (ViewState[_vsPeopleList] != null)
    {
        ViewState[_vsPeopleList] = null;
    }

    List<PeopleManagement> list = PeopleManagement.GetPeople(portfolio, year, month);

    ViewState[_vsPeopleList] = list;

    if(list.Count == 0)
    {
        gvPeople.Visible = false;
        lblAddError.Visible = true;
        lblAddError.Text = "No data available for current selection";
    }
    else
    {
        gvPeople.Visible = true;
        gvPeople.DataSource = list;
        gvPeople.DataBind();
    }
}

This method displays the data based on search filters.

I have 2 pages generated. 1st page has 10 records and 2nd page has 1 record.

When paging to the second page and clicking search again without changing any search filters, GridView still shows 1 record on the 2nd page. However, it should show 1st page with 10 records. Looks like, the GridView does not go back to the 1st page.

This is my PageIndexChanging method:

protected void gvPeople_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    lblAddError.Text = String.Empty;
    List<PeopleManagement> list = (List<PeopleManagement>)ViewState[_vsPeopleList];
    gvPeople.DataSource = list;
    gvPeople.PageIndex = e.NewPageIndex;
    gvPeople.DataBind();
}

I have no idea what is wrong. Trying to debug for sometime already. List has the same amount of records when is searched for the first time and when page's index is changed. Should be working fine...


Solution

  • Gene,

    it is because PageIndex property is set to new page you have navigated to. Just reset the PageIndex to Zero in the Search function.