1 // 1、定义几个所需的公有成员:
2
3 int pageSize = 0; //每页显示行数
4 int nMax = 0; //总记录数
5 int pageCount = 0; //页数=总记录数/每页显示行数
6 int pageCurrent = 0; //当前页号
7 int nCurrent = 0; //当前记录行
8 DataSet ds = new DataSet();
9 DataTable dtInfo = new DataTable();
10
11 //2、在窗体载入事件中,从数据源读取记录到DataTable中:
12
13 string strConn = "SERVER=127.0.0.1;DATABASE=NORTHWIND;UID=SA;PWD=ULTRATEL"; //数据库连接字符串
14 SqlConnection conn = new SqlConnection(strConn);
15 conn.Open();
16 string strSql = "SELECT * FROM CUSTOMERS";
17 SqlDataAdapter sda = new SqlDataAdapter(strSql,conn);
18 sda.Fill(ds,"ds");
19 conn.Close();
20 dtInfo = ds.Tables[0];
21 InitDataSet();
22
23 //3、用当前页面数据填充DataGridView
24
25 private void InitDataSet()
26 {
27 pageSize = 20; //设置页面行数
28 nMax = dtInfo.Rows.Count;
29 pageCount=(nMax/pageSize); //计算出总页数
30 if ((nMax % pageSize) > 0) pageCount++;
31 pageCurrent = 1; //当前页数从1开始
32 nCurrent = 0; //当前记录数从0开始
33 LoadData();
34 }
35
36 private void LoadData()
37 {
38 int nStartPos = 0; //当前页面开始记录行
39 int nEndPos = 0; //当前页面结束记录行
40 DataTable dtTemp = dtInfo.Clone(); //克隆DataTable结构框架
41
42 if (pageCurrent == pageCount)
43 {
44 nEndPos = nMax;
45 }
46 else
47 {
48 nEndPos = pageSize * pageCurrent;
49 }
50
51 nStartPos = nCurrent;
52 lblPageCount.Text = pageCount.ToString();
53 txtCurrentPage.Text = Convert.ToString(pageCurrent);
54
55
56 //从元数据源复制记录行
57 for (int i = nStartPos; i < nEndPos; i++)
58 {
59 dtTemp.ImportRow(dtInfo.Rows[i]);
60 nCurrent++;
61 }
62 bdsInfo.DataSource = dtTemp;
63 bdnInfo.BindingSource = bdsInfo;
64 dgvInfo.DataSource = bdsInfo;
65 }
66
67 // 4、菜单响应事件:
68
69 private void bdnInfo_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
70 {
71 if (e.ClickedItem.Text == "关闭")
72 {
73 this.Close();
74 }
75 if (e.ClickedItem.Text == "上一页")
76 {
77 pageCurrent--;
78 if (pageCurrent <= 0)
79 {
80 MessageBox.Show("已经是第一页,请点击“下一页”查看!");
81 return;
82 }
83 else
84 {
85 nCurrent = pageSize * (pageCurrent - 1);
86 }
87 LoadData();
88 }
89 if (e.ClickedItem.Text == "下一页")
90 {
91 pageCurrent++;
92 if (pageCurrent > pageCount)
93 {
94 MessageBox.Show("已经是最后一页,请点击“上一页”查看!");
95 return;
96 }
97 else
98 {
99 nCurrent=pageSize*(pageCurrent-1);
100 }
101 LoadData();
102 }
103 }
原文地址:https://www.cnblogs.com/zhujie-com/p/12363170.html