前文使用預存程序分頁雖高效,但缺乏代碼復用性。本文封裝通用分頁用戶控件,推薦吳琪娃 AspNetPager 組件。
AspNetPager.dll,工具箱右鍵「選擇項目」加入。AspNetPager 與 GridView/Repeater。private void BindData() {
string connStr = "server=.;database=Northwind;uid=sa;pwd=";
using (var con = new SqlConnection(connStr))
using (var sda = new SqlDataAdapter("select * from Customers", con)) {
var ds = new DataSet();
sda.Fill(ds);
var dv = ds.Tables[0].DefaultView;
var pds = new PagedDataSource {
DataSource = dv,
AllowPaging = true,
PageSize = AspNetPager1.PageSize,
CurrentPageIndex = AspNetPager1.CurrentPageIndex - 1
};
AspNetPager1.RecordCount = dv.Count;
GridView1.DataSource = pds;
GridView1.DataBind();
}
}
protected void AspNetPager1_PageChanged(object sender, EventArgs e) {
BindData();
}
BindData。PagedDataSource 為 .NET 內建分頁包裝器,支援任意 IEnumerable 資料源。