using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace dgvCategories { public partial class Form1 : Form { int _iPageSize = 0; //每页显示行数 int _iTotalRecords = 0; //总记录数 int _iPageCount = 0; //页数=总记录数/每页显示行数 int _iPageCurrent = 0; //当前页号 int _iCurrent = 0; //当前记录行 DataSet _ds = new DataSet(); DataTable _dtCategories = new DataTable(); public Form1() { InitializeComponent(); } private void InitDataSet() { _iPageSize = 20; //每页显示20行 _iTotalRecords = _dtCategories.Rows.Count; //表的总行数 _iPageCount = _iTotalRecords / _iPageSize; //总页数 if (_iTotalRecords % _iPageSize > 0) //如果不是整除, { _iPageCount++;//不满20行的也作为一页来显示 } _iPageCurrent = 1; //当前第1页 _iCurrent = 0; //当前第0行 LoadData(); } private void LoadData() { int iBeginPos = 0; //当前页面开始记录行 int iEndPos = 0; //当前页面结束记录行 DataTable dtTemp = _dtCategories.Clone(); //克隆表的结构 if (_iPageCurrent == _iPageCount) //如果当前页是最后一页 { iEndPos = _iTotalRecords; } else//当前页面结束位置=页面大小*当前页码 { iEndPos = _iPageSize * _iPageCurrent; } iBeginPos = _iCurrent; //当前记录行号 txtPageCount.Text = Convert.ToString(_iPageCount); //显示总页数 txtCurentPage.Text = Convert.ToString(_iPageCurrent); //显示当前第一页 //从元数据表复制数据 for (int i = iBeginPos; i < iEndPos; i++ ) { dtTemp.ImportRow(_dtCategories.Rows[i]); _iCurrent++; } dgvCategories.DataSource = bdsCategories; bdnCategories.BindingSource = bdsCategories; bdsCategories.DataSource = dtTemp; } private void Form1_Load(object sender, EventArgs e) { string strConnectionString = "server=localhost;database=NorthWind;" + "uid=sa;pwd=tianshi520;"; SqlConnection sqlConn = new SqlConnection(strConnectionString); sqlConn.Open(); string strSql = "select * from orders"; SqlDataAdapter sda = new SqlDataAdapter(strSql, sqlConn); sda.Fill(_ds, "Categories"); _dtCategories = _ds.Tables["Categories"]; sqlConn.Close(); InitDataSet(); } private void bdnCategories_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { if (e.ClickedItem.Text == "关闭") { this.Close(); } else if (e.ClickedItem.Text == "下一页") { _iPageCurrent++;//页数加1 if (_iPageCurrent > _iPageCount)//如果当前页码>最大页数 { MessageBox.Show("已经是最后一页,请点击“上一页”查看!"); return; } _iCurrent = _iPageSize * (_iPageCurrent - 1);//当前行号 LoadData(); } else if (e.ClickedItem.Text == "上一页") { _iPageCurrent--; if (_iPageCurrent <= 0) { MessageBox.Show("当前已经是第一页,请点击下一页查看!"); return; } _iCurrent = _iPageSize * (_iPageCurrent - 1); LoadData(); } } } }
时间: 2024-11-02 13:10:30