ASP.Net的GirdView在每次分頁處理時都會在重新抓取所有資料在進行分頁,遇到大量資料或是設計不良的情況下,在切換時頁面會卡住,造成使用者體驗不佳。
可以透過GirdView內建的參數以及SQL OFFSET語法來替代原先的分頁處理,以下為步驟說明
1.aspx加上GridView的幾個參數
AllowCustomPaging:自訂分頁處理旗標
AllowPage :是否允許分頁
<asp:GridView ... AllowCustomPaging="True" AllowPaging="True"> <PagerSettings Mode="Numeric"/> ...2.aspx.cs新增PageIndexChanging、btnQuery、GetData、GetDataCount方法
//分頁處理 protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e){ GridView1.PageIndex = e.NewPageIndex; GridView1.DataSource=GetData(e.NewPageIndex, e.PageSize); GridView1.DataBind(); } //查詢按鈕 protected void btnQuery(object sender){ GridView1.VirtualItemCount=GetDataCount(); GridView1.DataSource=GetData(0, 10); GridView1.DataBind(); } //透過SQL取得資料 private DataTable GetData(int PageIndex,int PageSize){ ... return GetDataBySQL(new Source{filter,PageIndex=PageIndex,PageSize=PageSize}); } //透過SQL取得資料總筆數 private DataTable GetDataCount(){ ... return GetDataCountBySQL(filter); }
#region 特殊處理
public int GetDataCountBySQL(filter filter){
//...回傳總筆數
}
public DataTable GetDataBySQL(filter filter,int PageIndex,int PageSize){
...
#region 分頁處理
if (!string.IsNullOrEmpty(PageIndex) && !string.IsNullOrEmpty(PageSize))
{
int pageIndex = 0;
int pageSize = 0;
if (int.TryParse(PageIndex, out pageIndex) && int.TryParse(PageSize, out pageSize))
{
sbSql.AppendLine($@"OFFSET {pageIndex * pageSize} ROWS FETCH NEXT {pageSize} ROWS ONLY");
}
}
#endregion
...
}