VS-利用AspNetPager控件实现真分页
Web开发中的分页常见的真分页假分页:此篇文章将讲解如何利用第三方控件(AspNetPager)实现真分页
1.下载AspNetPager控件:参考链接:http://www.webdiyer.com/Controls/AspNetPager/Downloads
2.引用AspNetPager控件,为自己所用。(右击工具箱-选择项)
3.界面与数据显示控件结合使用:(这里以GridView控件为例)
4.设置AspNetPager控件的属性:
PageSize:显示页数 (此例中设置为2)
5.后台代码:
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data;using System.Data.SqlClient;public partial class TruePage : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { //页面第一次加载 if (!Page.IsPostBack) { AspNetPager1.RecordCount = GetNum(); Bind(); } } //绑定数据方法 private void Bind() { SqlConnection con = CreateCon(); //使用cmd,DataAdapter结合dataSet ,利用存储过程 SqlCommand cmd = new SqlCommand("SelectPage", con); //给存储过程添加两个参数,一个AspNetPager当前页的开始记录索引和结束记录索引 SqlParameter sp1 = new SqlParameter("@startPageIndex",AspNetPager1 .StartRecordIndex ); SqlParameter sp2 = new SqlParameter("@endPageIndex", AspNetPager1.EndRecordIndex); cmd.Parameters.Add(sp1); cmd.Parameters.Add(sp2); cmd.CommandType = CommandType.StoredProcedure; DataSet ds = new DataSet(); SqlDataAdapter sda = new SqlDataAdapter(cmd); sda.Fill(ds, "User"); GridView1.DataSource = ds.Tables["User"]; GridView1.DataBind(); } //创建数据库连接对象 private SqlConnection CreateCon() { SqlConnection con = new SqlConnection("server=.;database=User;uid=sa;pwd=123456"); con.Open(); return con; } //查询某个数据表的记录条数方法 private int GetNum() { SqlConnection con = CreateCon(); SqlCommand cmd = new SqlCommand("select Count(*) from UserInfo", con); int num=(int)cmd.ExecuteScalar(); return num ; } //当前页变化时,重新绑定数据 protected void AspNetPager1_PageChanged(object sender, EventArgs e) { Bind(); }}
6.存储过程代码:
CREATE PROCEDURE [dbo].[SelectPage]@startPageIndex int ,@endPageIndex intASBEGIN-- 建立一个临时表,利用ROW_NUMBER函数增添新列row,按顺序排列,参照牛腩with temptb as(select ROW_NUMBER() OVER(ORDER BYAge desc) as row, * from UserInfo) -- 在临时表中按照开始记录索引和结束记录索引值来查询记录select * from temptb where Row between @startPageIndex and @endPageIndexEND
最终显示效果: