using System; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; namespace DataGridViewDataNavigate { public partial class Form1 : Form { public Form1() { InitializeComponent(); } SqlDataAdapter sqladp; DataSet dateSet = new DataSet(); private int startVal=0;//起始值 private int perPageVal = 3;//每页显示数量 private int totalVal;//总条数 private int currentPage=0;//当前页 private void Form1_Load(object sender, EventArgs e) { string constr = @"server=(localdb)\Projects;integrated security=sspi;database=company"; SqlConnection sqlcon = new SqlConnection(constr); try { sqlcon.Open(); string sql = "select * from clerk"; sqladp = new SqlDataAdapter(sql,sqlcon); sqladp.Fill(dateSet,"clerk"); //this.dataGridView1.DataSource = dateSet.Tables["clerk"]; sqlcon.Close(); //计算总页数 totalVal = dateSet.Tables["clerk"].Rows.Count; int totalPage=(totalVal%perPageVal==0)?(totalVal/perPageVal):(totalVal/perPageVal+1); lblTotalPage.Text = "/" + totalPage; LoadData(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void LoadData() { //显示当前页面 currentPage = startVal / perPageVal + 1; txtCurrentPage.Text = currentPage.ToString(); //绑定数据 dateSet.Clear(); sqladp.Fill(dateSet, startVal, perPageVal, "clerk"); bindingSource1.DataSource=dateSet.Tables[0]; bindingNavigator1.BindingSource = bindingSource1; dataGridView1.DataSource = bindingSource1; } private void bindingNavigator1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { if (e.ClickedItem.Text == "上一页") { startVal = startVal - perPageVal; if (startVal < 0) { startVal = 0; MessageBox.Show("已经是第一页"); return; } } if (e.ClickedItem.Text == "下一页") { startVal = startVal + perPageVal; if (startVal > totalVal) { startVal = startVal - perPageVal; MessageBox.Show("已经是最后一页"); return; } } LoadData(); } } }