winform里dataGridView分頁,默認dataGridView是不分頁的和webform里不一樣,webform中GridView自帶自帶了分頁。
現在c/s的程序很多時候也需要webform的分頁樣式,所以就寫了下面的分頁,使用了access數據庫。
原理就是讀取數據存入datatable中,然后根據不同的頁來顯示當頁數據。這樣有個缺點就是數據量太大時會影響顯示速度。sql server數據庫時可以借助數據庫來實現只讀取當頁數據來顯示,效率會高一些。
所用環境:vs.net2010 access2003
form中控件如下圖:
控件分別是:dataGridView1,button1,button3,button2,button4,textBox1,button5,label2,label3,label4,label5,label6,label7
分頁效果如下圖:
代碼如下:
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 = 10; //每頁記錄數 public int recordCount = 0; //總記錄數 public int pageCount = 0; //總頁數 public int currentPage = 0; //當前頁 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) > 0) { pageCount++; } //默認第一頁 currentPage = 1; LoadPage(); } private void LoadPage() { // if (currentPage < 1) currentPage = 1; if (currentPage > pageCount) currentPage = pageCount; // int beginRecord; int endRecord; DataTable dtTemp; dtTemp = dtSource.Clone(); beginRecord = pageSize * (currentPage - 1); if (currentPage == 1) beginRecord = 0; 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 = 1; 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