- 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();
- }
- }
- }
C#编程-79:DataGridView分页显示
原创
©著作权归作者所有:来自51CTO博客作者彭世瑜的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
C#读取Excel文件并用datagridview显示
试过网上大部分方法
向下兼容 连接字符串 Click