C#实现Datagridview分页,从Sql中读取的数据
首先简单的需要 初始化分页显示的参数,我所需要的就是总页数,当前页,总行数,返回行数(此为绑定dgv中显示的行数),从第几行开始返回。
1.申明变量:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #region 初始化分页显示的参数 2 static int rowsall = 0;//总行数 3 static int pageall = 0;//总页数 4 static int page = 0;//第几页 5 static int count = 5;//返回5行 6 static int start = 0;//从第start行开始返回 7 #endregion
2.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /// <summary> 2 /// 设置DataGridView分页显示的参数,和初次绑定 3 /// </summary> 4 /// <param name="sqlstr">设置查询的sql语句</param> 5 /// <param name="table">设置返回绑定的DataSet中的表的名称</param> 6 /// <param name="dgv">要绑定的DataGridView</param> 7 public void upPage(string sqlstr,string table,DataGridView dgv) 8 { 9 rowsall = getds(sqlstr, table).Tables[table].Rows.Count;//总行数 10 if (rowsall == 0) 11 { 12 //如果没有数据则将第一页、上一页、下一页、最后一页设置为不可用;并设置其他参数 13 14 page = 0; 15 pageall = 0; 16 rowsall = 0; 17 dgv.DataSource = null; 18 toolStripLabel3.Text = pageall.ToString(); 19 toolStripTextBox3.Text = page.ToString(); 20 return; 21 } 22 if (rowsall > 0)//判断是否有内容 23 { 24 page = 1;//如果有内容,设置为第一页 25 start = 0; 26 } 27 int yushu = rowsall % count;//是否存在余行 28 if (yushu == 0)//不存在余行时设置总页数 29 { 30 if (rowsall > 0 && rowsall <= count) 31 { 32 pageall = 1; 33 } 34 else 35 { 36 pageall = rowsall / count; 37 } 38 } 39 else//存在余行时设置总页数 40 { 41 pageall = rowsall / count + 1; 42 } 43 {//设置显示数据, 我没有显示总行数 44 45 toolStripLabel3.Text = pageall.ToString(); 46 toolStripTextBox3.Text = page.ToString(); 47 if (pageall > 0) 48 { //设置跳转到第几页 49 50 tscbPage.Items.Clear(); 51 for (int i = 1; i <= pageall; i++) 52 tscbPage.Items.Add(i); 53 } 54 } 55 56 selectsql = sqlstr; 57 dgvSenderMess.DataSource = gettb(selectsql, start, count, "t_News");//绑定DataGridView 58 59 } 60 #endregion
3.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public DataTable gettb(string sql, int start, int count, string tablename) 2 { 3 OleDbConnection SQLConnection = new OleDbConnection("Provider=SQLOLEDB;Data Source=" + ServerName + ";User ID=" + User + ";PWD=" + Pwd + ";Initial Catalog=" + Name + ""); 4 SQLConnection.Open(); 5 DataSet myds = new DataSet(); 6 OleDbDataAdapter sda = new OleDbDataAdapter(sql, SQLConnection); 7 8 sda.Fill(myds, start, count, tablename); 9 return myds.Tables[tablename]; 10 }
public DataSet getds(string M_str_sqlstr, string M_str_table) { DataSet myds = new DataSet(); OleDbConnection SQLConnection = new OleDbConnection("Provider=SQLOLEDB;Data Source=" + ServerName + ";User ID=" + User + ";PWD=" + Pwd + ";Initial Catalog=" + Name + ""); SQLConnection.Open(); OleDbDataAdapter sqlda = new OleDbDataAdapter(M_str_sqlstr, SQLConnection); sqlda.Fill(myds, M_str_table); return myds; }
4.在窗体中添加bindingNavigator控件,自己添加需要的,label,和textbox。