Search code examples
c#asp.netgridviewpaginationpage-index-changed

asp.net gridview dynamically binding


i have a GridView,

<asp:GridView ID="managerList" runat="server" DataSourceID="SqlDataSource2">

in the code behind,

protected void Page_Load(object sender, EventArgs e)
{
    SqlDataSource2.SelectCommand = "select * from manager";
    managerList.AllowPaging = true;
}

when i load the page, it works fine, the paging works fine, too.

Then i want to get the subset of the list by click on a search button:

protected void btnSearch_Click(object sender, EventArgs e)
{
    SqlDataSource2.SelectCommand = "select * from manager where age > 30";
    managerList.DataBind();
}

it works fine, give me the subset of the list.

However, when i click on "next page", it gives me the whole list, page #2. I know it's because it sends a postback, and it bind the original select command. But how can i do to give me the subset of the list when i click on "next page"?

Thank you!

UPDATES: if i change the code into this:

protected void Page_Load(object sender, EventArgs e)
{
  if(!IsPostBack)
  {
    SqlDataSource2.SelectCommand = "select * from manager";
    managerList.AllowPaging = true;
  }
}

it gives me an empty list when i click on "next page".

it might be tempted to add IsPostBack, but this not work.


Solution

  • Add the NewPageIndex code in the PageIndexChanging event:

    managerList.PageIndex = e.NewPageIndex;
    bindgrid();