这几天无意间看到一个关于分页的帖子,觉得写得挺好的。关于这些东西,自己一直都是只知道原理,却没有真正动手做过,于是研究了一下分页的原理自己动手写了一个十分特别非常简单的分页程序,在这里与大家分享一下。
这个程序取数据使用的ado.net,首先先新建一个取数据的类PageDAl
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Web; namespace page.DAL { public class PageDal { public DataTable GetUserList(out int totalCount, int pageIndex = 1, int pagesize = 10) { using ( SqlConnection coon = new SqlConnection(ConfigurationManager.ConnectionStrings["userConnection"].ConnectionString)) { coon.Open(); string sqlCount = "select count(F_Id) from Sys_User"; SqlCommand cmd = new SqlCommand(sqlCount, coon); totalCount = int.Parse(cmd.ExecuteScalar().ToString()); string sql = "select F_Account,F_RealName from (select *,Row_Number() over(order by F_Account) r from Sys_User)as w where r>{0} and r<={1};"; SqlDataAdapter ad = new SqlDataAdapter(String.Format(sql, (pageIndex - 1) * pagesize, (pageIndex * pagesize)), coon); DataTable dt = new DataTable(); ad.Fill(dt); return dt; } } } }
然后记得修改一下webconfig里面的连接数据库的字符串,数据库自己随便建一个就行。
接下来是ashx一般处理程序,html页面把需求传过来,他在从PageDal中取数据。
using page.DAL; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Web; namespace page { /// <summary> /// WebHandler 的摘要说明 /// </summary> public class WebHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { try { int pageIndex = int.Parse(context.Request.Form["pageindex"]); int pageSize = int.Parse(context.Request.Form["pagesize"]); PageDal pd = new PageDal(); int totalCount; DataTable dt = pd.GetUserList(out totalCount, pageIndex, pageSize); string json = ToJson(dt, "data", totalCount); context.Response.ContentType = "text/plain"; context.Response.Write(json); } catch { context.Response.Write("error"