使用winform的dataGridView控件實現簡單的分頁
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace 分頁 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private int pageIndex = 1; //當前的頁碼 private int pageSize = 7; //每頁顯示的記錄 private int pageCount = 0; //總的頁數 private int recordCount = 0; //總的記錄 private void Form1_Load(object sender, EventArgs e) { loadData(); } private void loadData() { //連接字符串 string constr = "Data source=SZS\\SQLEXPRESS;INITIAL CATALOG=mysql;integrated Security=true"; using (SqlConnection conn = new SqlConnection(constr)) { string sql = "usp_fenye"; //sql語句變成存儲過程名 DataTable dt = new DataTable(); using (SqlDataAdapter sqlData =new SqlDataAdapter(sql, constr)) { //表示要執行的是存儲過程 sqlData.SelectCommand.CommandType = CommandType.StoredProcedure; //增加參數 SqlParameter[] pms = new SqlParameter[] { new SqlParameter("@pagesize",SqlDbType.Int){ Value=pageSize}, new SqlParameter("@index",SqlDbType.Int){ Value=pageIndex}, new SqlParameter("@recordcount",SqlDbType.Int){Direction=ParameterDirection.Output}, new SqlParameter("@pagecount",SqlDbType.Int){ Direction=ParameterDirection.Output}, }; sqlData.SelectCommand.Parameters.AddRange(pms); sqlData.Fill(dt); //獲取輸出的參數 label1.Text = pms[2].Value.ToString(); recordCount = Convert.ToInt32(label1.Text); label2.Text = pms[3].Value.ToString(); pageCount = Convert.ToInt32(label2.Text); label6.Text = pageIndex.ToString(); this.dataGridView1.DataSource = dt; } } } //上一頁 private void button1_Click(object sender, EventArgs e) { if (pageIndex>1) { pageIndex--; loadData(); } } //下一頁 private void button2_Click(object sender, EventArgs e) { if (pageIndex< pageCount) { pageIndex++; loadData(); } } } }
結果: