1 public partial class _Default : System.Web.UI.Page 2 { 3 private mydbDataContext _context = new mydbDataContext();//建立连接 4 private const int PAGESIZE = 3;//定义每页大小为三个 5 6 //取得分页信息************重要*********** 7 public List<Car> GetPageCar(int pageNo) 8 { 9 var query = _context.Car.Skip(PAGESIZE * (pageNo - 1)).Take(PAGESIZE); 10 return query.ToList(); 11 } 12 13 //获取总页数************重要*********** 14 public int GetPageCount() 15 { 16 int rowsCount = _context.Car.Count();//获得总行数 17 int pageCount = (int)Math.Ceiling(1.0 * rowsCount / PAGESIZE); 18 return pageCount; 19 } 20 21 22 protected void Page_Load(object sender, EventArgs e) 23 { 24 int nowPage =1;//初始页为1 25 if (Request["pageno"]!=null)//第一次打开pageno为空,当不为空的时候就给nowpage赋值 26 { 27 nowPage = Convert.ToInt32(Request["pageno"]); 28 } 29 //显示列表中的信息 30 ShowPageCars(nowPage); 31 32 //显示上一页下一页的数据,首页和尾页 33 ShowPrevNextLink(nowPage); 34 35 } 36 37 //显示上一页下一页首页尾页信息 38 private void ShowPrevNextLink(int nowPage) 39 { 40 //给上一页,下一页数据 41 int pageCount = GetPageCount(); 42 //控制下一页连接 43 if (nowPage == pageCount) 44 { 45 linkNext.Enabled = false; 46 linkLast.Enabled = false; 47 } 48 else 49 { 50 linkNext.Enabled = true; 51 linkLast.Enabled = true; 52 linkNext.NavigateUrl = "Default.aspx?pageno=" + (nowPage + 1).ToString(); 53 //控制尾页 54 linkLast.NavigateUrl = "Default.aspx?pageno=" + pageCount; 55 } 56 //控制上一页连接 57 if (nowPage == 1) 58 { 59 linkPrev.Enabled = false; 60 linkFrist.Enabled = false; 61 } 62 else 63 { 64 linkPrev.Enabled = true; 65 linkFrist.Enabled = true; 66 linkPrev.NavigateUrl = "Default.aspx?pageno=" + (nowPage - 1).ToString(); 67 //控制首页连接 68 linkFrist.NavigateUrl = "Default.aspx?pageno=1"; 69 } 70 } 71 72 //显示列表信息 73 private void ShowPageCars(int nowPage) 74 { 75 List<Car> list = GetPageCar(nowPage); 76 //给Repeater数据 77 Repeater1.DataSource = list; 78 Repeater1.DataBind(); 79 } 80 81 //跳转 82 protected void btnGo_Click(object sender, EventArgs e) 83 { 84 if (txtPageNO.Text == "") 85 { 86 87 } 88 else 89 { 90 int goNo = Convert.ToInt32(txtPageNO.Text); 91 if (goNo < 1) 92 { 93 Response.Redirect("Default.aspx"); 94 } 95 else if (goNo > GetPageCount()) 96 { 97 Response.Redirect("Default.aspx?pageno=" + GetPageCount()); 98 } 99 else 100 { 101 Response.Redirect("Default.aspx?pageno=" + goNo); 102 } 103 } 104 } 105 }
效果图如下
首页(name): linkFirst
上一页(name):linkPrev
下一页(name):,linkNext
尾页(name):linkLast
以上都是HyperLink控件(超链接)
文本框(name):txtPageNo
跳转按钮(name):btnGo
分页问题,每次点击页面都将从新加载.可考虑Ajax优化
时间: 2024-10-10 03:46:26