[C#] - DataGridView分页
来源:http://xinyuan178.blog.163.com/blog/static/49799652200942342122524/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int pageSize = 0; // 每页显示行数
int pageCount = 0; // 页数=总记录数/每页显示行数
int recordCount = 0; // 总记录数
int curPageNum = 0; // 当前页号
int curRowNum = 0; // 当前记录行
DataSet DS = new DataSet();
DataTable dtInfo = new DataTable();
private void Form1_Load(object sender, EventArgs e)
{
string connStr = "Server=localhost;Database=Northwind;UID=sa;Pwd=;";
string cmdStr = "Select * from [Customers]";
using (SqlConnection sqlConn = new SqlConnection(connStr))
{
sqlConn.Open();
using (SqlDataAdapter sqlDA = new SqlDataAdapter(cmdStr, sqlConn))
{
sqlDA.Fill(DS);
}
sqlConn.Close();
}
dtInfo = DS.Tables[0];
InitDataSet();
}
private void InitDataSet()
{
pageSize = 10; // 设置页面行数
recordCount = dtInfo.Rows.Count;
pageCount = (recordCount / pageSize); // 计算出总页数
if ((recordCount % pageSize) > 0) { pageCount++; }
curPageNum = 1; // 当前页数从1开始
curRowNum = 0; // 当前记录数从0开始
LoadData();
}
private void LoadData()
{
int startPos = 0; // 当前页面开始记录行
int endPos = 0; // 当前页面结束记录行
DataTable dtTemp = dtInfo.Clone(); // 克隆DataTable结构框架
if (curPageNum == pageCount)
{
endPos = recordCount;
}
else
{
endPos = pageSize * curPageNum;
}
startPos = curRowNum;
label1.Text = string.Format("第{0}页/共{1}页", curPageNum, pageCount);
// 从元数据源复制记录行
for (int i = startPos; i < endPos; i++)
{
dtTemp.ImportRow(dtInfo.Rows[i]);
curRowNum++;
}
dataGridView1.DataSource = dtTemp;
}
// 三个按钮的事件
private void ButtonClicked(object sender, EventArgs e)
{
switch (((Button)sender).Text)
{
case "上一页":
curPageNum--;
if (curPageNum <= 0)
{
curPageNum = 0;
MessageBox.Show("已经是第一页,请点击“下一页”查看!");
return;
}
curRowNum = pageSize * (curPageNum - 1);
LoadData();
break;
case "下一页":
curPageNum++;
if (curPageNum > pageCount)
{
curPageNum = pageCount;
MessageBox.Show("已经是最后一页,请点击“上一页”查看!");
return;
}
curRowNum = pageSize * (curPageNum - 1);
LoadData();
break;
case "关闭":
this.Close();
Application.Exit();
break;
default:
break;
}
}
}
个性签名:做要做好,做到不三不四不如不做。