问题
I have gridview with multiple pages of records in a.aspx. When I click a button in b.aspx I need to go to a specific page that contains the record in the gridview.
回答1:
I assume that you actually want to go to a specific record instead. Then i would pass it's ID via url-parameter (or session) and then go to the page in the grid with this record. That's is better because the page might change(f.e. with sorting).
Assuming that your grid lists products and you want to ensure that a perticular product is shown because you've just edited the product-details on another page. Also assuming that your DataSource is a DataTable(but it doesn't really matter):
/// <summary>
/// Binds the products-GridView.
/// </summary>
/// <param name="ProductID">the ProductID to be displayed, changes also the PageIndex if necessary</param>
private void BindProductGrid(int ProductID = -1)
{
DataTable tblProducts = getAllProducts();
GridProducts.DataSource = tblProducts;
bool needsPaging = (tblProducts.Rows.Count / GridProducts.PageSize) > 1;
if (ProductID == -1)
{
this.GridProducts.PageIndex = 0;
this.GridProducts.SelectedIndex = -1;
}
else
{
int selectedIndex = tblProducts.AsEnumerable()
.Select((Row, Index) => new { Row, Index })
.Single(x => x.Row.Field<int>("ProductID") == ProductID).Index;
int pageIndexofSelectedRow = (int)(Math.Floor(1.0 * selectedIndex / GridProducts.PageSize));
GridProducts.PageIndex = pageIndexofSelectedRow;
GridProducts.SelectedIndex = (int)(GridProducts.PageIndex == pageIndexofSelectedRow ? selectedIndex % GridProducts.PageSize : -1);
}
GridProducts.DataBind();
}
来源:https://stackoverflow.com/questions/13305316/how-to-go-to-particular-record-in-gridview