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;
namespace LabSys_demo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int pageSize = 0; //每页显示行数
int nMax = 0; //总记录数
int pageCount = 0; //页数=总记录数/每页显示行数
int pageCurrent = 0; //当前页号
int nCurrent = 0; //当前记录行
private void Form1_Load(object sender, EventArgs e)
{
InitDataSet();
}
public DataTable GetDataTable()
{
DataTable dt = new DataTable();
DataColumn c1 = new DataColumn("序号", typeof(string));
DataColumn c2 = new DataColumn("名称", typeof(string));
DataColumn c3 = new DataColumn("职位", typeof(string));
dt.Columns.Add(c1);
dt.Columns.Add(c2);
dt.Columns.Add(c3);
for (int i = 0; i < 10; i++)
{
dt.Rows.Add(i+1, "测试"+(i+1), "工人"+(i+1));
}
return dt;
}
private void InitDataSet()
{
pageSize = 2; //设置页面行数
nMax = GetDataTable().Rows.Count;
pageCount = (nMax / pageSize); //计算出总页数
if ((nMax % pageSize) > 0) pageCount++;
pageCurrent = 1; //当前页数从1开始
nCurrent = 0; //当前记录数从0开始
LoadData();
}
private void LoadData()
{
int nStartPos = 0; //当前页面开始记录行
int nEndPos = 0; //当前页面结束记录行
DataTable dtTemp = GetDataTable().Clone(); //克隆DataTable结构框架
if (pageCurrent == pageCount)
nEndPos = nMax;
else
nEndPos = pageSize * pageCurrent;
nStartPos = nCurrent;
lblPageCount.Text = pageCount.ToString();
txtCurrentPage.Text = Convert.ToString(pageCurrent);
//从元数据源复制记录行
for (int i = nStartPos; i < nEndPos; i++)
{
dtTemp.ImportRow(GetDataTable().Rows[i]);
nCurrent++;
}
dataGridView1.DataSource = dtTemp;
dataGridView1.AllowUserToAddRows = false;
}
/// <summary>
/// 下一页
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void lbl_next_Click(object sender, EventArgs e)
{
pageCurrent++;
if (pageCurrent > pageCount)
{
MessageBox.Show("已经是最后一页,请点击“上一页”查看!");
return;
}
else
{
nCurrent = pageSize * (pageCurrent - 1);
}
LoadData();
}
/// <summary>
/// 上一页
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void lbl_up_Click(object sender, EventArgs e)
{
pageCurrent--;
if (pageCurrent <= 0)
{
MessageBox.Show("已经是第一页,请点击“下一页”查看!");
return;
}
else
{
nCurrent = pageSize * (pageCurrent - 1);
}
LoadData();
}
}
}