主要实现页面跳转、动态改变每页显示行数、返回首末页、上下页功能,效果图如下:
主代码如下:
namespace Paging
{public partial class Form1 : Form{public Form1(){InitializeComponent();}private int currentPageCount;//记录当前页行数private int pageCount;//记录总页数private int currentCount;//记录当前页数private void Form1_Load(object sender, EventArgs e){currentPageCount = Convert.ToInt32(txt_lines.Text);string sql = "select*from StudentInfo";DataSet ds = ConnectClass.ReturnDataSet(sql);Paging(ds);}private void Paging(DataSet ds){int pageLine = 0;int count = ds.Tables[0].Rows.Count;//总行数lb_recordNum.Text = count.ToString();pageCount = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(count) / currentPageCount));if (count > currentPageCount)pageLine = currentPageCount;elsepageLine = count;this.currentCount = 1;Binds();}private void btn_Click(object sender, EventArgs e){Button btn = sender as Button;string tag = btn.Tag.ToString();//获取首页、上一页、下一页、末页的tag属性值switch (tag){case "0"://首页this.currentCount = 1;break;case "1"://上一页this.currentCount -= 1;break;case "2"://下一页this.currentCount += 1;break;case "3"://末页this.currentCount = this.pageCount;break;}Binds();}private void Binds(){string sql = string.Empty;if (this.currentCount.Equals(0)){currentCount = 1;MessageBox.Show("当前已是首页");}else if (this.currentCount.Equals(pageCount + 1)){this.currentCount = this.pageCount;MessageBox.Show("当前已是末页");}else if (this.currentCount > 0 && this.currentCount < pageCount + 1){sql = ConnectClass.ReturnSelectSql(currentPageCount, (currentCount - 1) * currentPageCount);DataSet ds = ConnectClass.ReturnDataSet(sql);this.dataGridView1.DataSource = ds.Tables[0];lb_page.Text = this.currentCount + " / " + pageCount;}}//跳转页面private void btn_jump_Click(object sender, EventArgs e){if (txt_page.Text == "")return;this.currentCount = Convert.ToInt32(txt_page.Text);if (this.currentCount > 0 && this.currentCount < pageCount + 1)Binds();}//设置每行页数private void txt_lines_Leave(object sender, EventArgs e){Form1_Load(sender, e);}}
}
ConnectClass类文件代码如下:
namespace Paging
{class ConnectClass{private static string sqlCon = "Data source=.;Initial Catalog=StudentInfo;Integrated Security=True;";private static SqlConnection conn = new SqlConnection(sqlCon);public static DataSet ReturnDataSet(string sql){conn.Open();DataSet ds = new DataSet();SqlDataAdapter sda = new SqlDataAdapter(sql, conn);sda.Fill(ds, "objDataSet");conn.Close();return ds;}public static string ReturnSelectSql(int count,int totalCount){string sql = "select top " + count + " * from StudentInfo where id not in (select top " + totalCount + " id from StudentInfo) ";return sql;}}
}
转载:c#winform控件datagridview实现分页效果_Jakie_Zhan的博客-CSDN博客