DateGridView 分页显示
l 思路:将数据表整体填充至一个Dataset中,探后部分显示(DataaAdapter Fill重载)
l DataGridView 控件
l BindingNavigator 控件
l Bindingsource 组件
private int startval = 0;//设置起始页 private int valperpage = 3;//设置每页要显示的条目数 private int totalvalNumber;//总条数 private int currentpage=1;//当前页 private SqlDataAdapter mydpt; private DataSet mydt; //窗体加载 private void Form1_Load(object sender, EventArgs e) { string constr = "server=192.168.100.222;user=sa;pwd=p@ssw1rd;database=pwd1"; string sql = "select * from book"; SqlConnection mycon = new SqlConnection(constr); mycon.Open(); mydpt = new SqlDataAdapter(sql,mycon); mydt = new DataSet(); mydpt.Fill(mydt,"book"); mycon.Close(); totalvalNumber = mydt.Tables[0].Rows.Count; //总页数计算 int totalpageNumber = (totalvalNumber % valperpage == 0) ? (totalvalNumber / valperpage) : (totalvalNumber / valperpage + 1); //设置标签显示 toolStripLabel1.Text ="/"+ totalpageNumber; LoadData(); } //创建绑定方法 private void LoadData() { currentpage = startval / valperpage + 1; toolStripTextBox1.Text = currentpage.ToString(); mydt.Clear(); mydpt.Fill(mydt,startval,valperpage,"book");//SQLdateadapt 填充的方法重载(填充的dataset,起始页,每页多少条目,哪个表) bindingSource1.DataSource=mydt.Tables[0];//组件bindingsource 等于dataset.表book填充。 bindingNavigator1.BindingSource = bindingSource1;//bindingnavigaor导航.bindingsource=bindingsource 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(); } //这样写也是可以的!!!!!!!!!!!!!!!!!!!!!!! //点击上一页事件 private void toolStripButton1_Click(object sender, EventArgs e) { startval = startval - valperpage; if (startval<0) { MessageBox.Show("已经是第一页"); startval = 0; return; } LoadData(); } //点击下一页事件 private void toolStripButton2_Click(object sender, EventArgs e) { startval = startval + valperpage; if (startval>totalvalNumber) { MessageBox.Show("已经是最后一页"); startval = startval - valperpage; return; } LoadData(); }