页面的GridView表格属性需要添加 OnRowDataBound=”GridView1_RowDataBound” 和 OnPageIndexChanging=”GridView1_PageIndexChanging”属性
/// <summary>
/// Gridview点击分页按钮,触发事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
// 得到该控件
GridView theGrid = sender as GridView;
int newPageIndex = 0;
if (e.NewPageIndex == -3)
{
//点击了Go按钮
TextBox txtNewPageIndex = null;
//GridView较DataGrid提供了更多的API,获取分页块可以使用BottomPagerRow 或者TopPagerRow,当然还增加了HeaderRow和FooterRow
GridViewRow pagerRow = theGrid.BottomPagerRow;
if (pagerRow != null)
{
//得到text控件
txtNewPageIndex = pagerRow.FindControl("txtNewPageIndex") as TextBox;
}
if (txtNewPageIndex != null)
{
//得到索引
newPageIndex = int.Parse(txtNewPageIndex.Text) - 1;
}
}
else
{
//点击了其他的按钮
newPageIndex = e.NewPageIndex;
}
//防止新索引溢出
newPageIndex = newPageIndex < 0 ? 0 : newPageIndex;
newPageIndex = newPageIndex >= theGrid.PageCount ? theGrid.PageCount - 1 : newPageIndex;
//得到新的值
theGrid.PageIndex = newPageIndex;
//重新绑定
InitGridView();
}
/// <summary>
/// GridView表格内数据排序
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//跳转页面后,序号连续
if (e.Row.RowIndex != -1)
{
int indexID = this.GridView1.PageIndex * this.GridView1.PageSize + e.Row.RowIndex + 1;
e.Row.Cells[0].Text = indexID.ToString();
}
}
本文详细介绍了如何在ASP.NET中使用GridView控件实现自定义分页和排序功能。通过添加OnRowDataBound和OnPageIndexChanging事件,可以有效管理大量数据的显示,提升用户体验。
257

被折叠的 条评论
为什么被折叠?



