15.12DataGridView分页显示
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 _15._11DataGridView分页显示 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private SqlDataAdapter pagingDA; private DataSet pagingDS = new DataSet(); private int startVal = 0; private int valPerPage = 3;//每页显示的内容 private int totalValNumber;//总条数 private int currPage = 1;//当前页数 private void Form1_Load(object sender, EventArgs e) { // TODO: 这行代码将数据加载到表“csharpzxwDataSet.mytable001”中。您可以根据需要移动或删除它。 // this.mytable001TableAdapter.Fill(this.csharpzxwDataSet.mytable001); string constr = "Server=.;uid=sa;pwd=zqyo850619;database=csharpzxw"; SqlConnection mycon = new SqlConnection(constr); try { mycon.Open(); string sql = "select * from mytable001"; pagingDA = new SqlDataAdapter(sql, mycon); pagingDA.Fill(pagingDS, "mytable001"); totalValNumber = pagingDS.Tables[0].Rows.Count; int totalPageNumber = (totalValNumber % valPerPage == 0) ? (totalValNumber / valPerPage) : (totalValNumber / valPerPage + 1);//三元运算符求页数,分可以蒸出和不能整除两种情况 toolStripLabel1.Text = "/" + totalPageNumber; loadData(); } catch(Exception ex) { MessageBox.Show(ex.Message); } finally { mycon.Close(); } } private void loadData() { currPage = startVal / valPerPage + 1;//当前页 toolStripTextBox1.Text = currPage.ToString(); pagingDS.Clear(); pagingDA.Fill(pagingDS, startVal, valPerPage, "mytable001"); bindingSource1.DataSource = pagingDS.Tables[0]; bindingNavigator1.BindingSource = bindingSource1; dataGridView1.DataSource = bindingSource1; } private void bindingNavigator1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { if (e.ClickedItem.Text == "上一页") { startVal = startVal - valPerPage; if (startVal < 0) { MessageBox.Show("已经是第一页"); startVal = 0; return; } } if (e.ClickedItem.Text == "下一页") { startVal = startVal + valPerPage; if (startVal > totalValNumber) { MessageBox.Show("已经是最后一页"); startVal = startVal = valPerPage; return; } } loadData(); } } }