winform里dataGridView分页代码,access数据库

winform里dataGridView分页,默认dataGridView是不分页的和webform里不一样,webform中GridView自带自带了分页。

现在c/s的程序很多时候也需要webform的分页样式,所以就写了下面的分页,使用了access数据库。

原理就是读取数据存入datatable中,然后根据不同的页来显示当页数据。这样有个缺点就是数据量太大时会影响显示速度。sql server数据库时可以借助数据库来实现只读取当页数据来显示,效率会高一些。

所用环境:vs.net2010   access2003

form中控件如下图:

winform里dataGridView分页代码,access数据库

控件分别是:dataGridView1,button1,button3,button2,button4,textBox1,button5,label2,label3,label4,label5,label6,label7

分页效果如下图:

winform里dataGridView分页代码,access数据库

代码如下:

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 test
{
public partial class Form3 : Form
{
public int pageSize = ; //每页记录数
public int recordCount = ; //总记录数
public int pageCount = ; //总页数
public int currentPage = ; //当前页 public DataTable dtSource = new DataTable(); public Form3()
{
InitializeComponent();
} private void Form3_Load(object sender, EventArgs e)
{
//数据库操作获得DataTable
string sql = "select ID,title from info"; DB db = new DB(); dtSource = db.GetDt(sql);
// recordCount = dtSource.Rows.Count; pageCount = (recordCount / pageSize); if ((recordCount % pageSize) > )
{
pageCount++;
} //默认第一页
currentPage = ; LoadPage();
} private void LoadPage()
{
//
if (currentPage < ) currentPage = ;
if (currentPage > pageCount) currentPage = pageCount;
// int beginRecord;
int endRecord;
DataTable dtTemp; dtTemp = dtSource.Clone(); beginRecord = pageSize * (currentPage - );
if (currentPage == ) beginRecord = ;
endRecord = pageSize * currentPage;
if (currentPage == pageCount) endRecord = recordCount; for (int i = beginRecord; i < endRecord; i++)
{
dtTemp.ImportRow(dtSource.Rows[i]);
} dataGridView1.DataSource = dtTemp; label3.Text = currentPage.ToString();
label5.Text = pageCount.ToString();
label7.Text = recordCount.ToString();
textBox1.Text = currentPage.ToString();
} private void button1_Click(object sender, EventArgs e)
{
currentPage = ;
LoadPage();
}
private void button2_Click(object sender, EventArgs e)
{
currentPage++;
LoadPage();
}
private void button3_Click(object sender, EventArgs e)
{
currentPage--;
LoadPage();
}
private void button4_Click(object sender, EventArgs e)
{
currentPage = pageCount;
LoadPage();
} private void button5_Click(object sender, EventArgs e)
{
int pageN = Convert.ToInt32(textBox1.Text);
currentPage = pageN;
LoadPage();
} }
}

数据库access2003

winform里dataGridView分页代码,access数据库

上一篇:ibatis解决sql注入问题


下一篇:Spring中的JdbcTemplate使用