Datagridview控件实现分页功能

可以进行sql语句进行设置:
   
   1.先新建一个窗体,一个DataGridView控件、两个label控件、两个Button控件
   2.代码如下:

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace _2012_4_7
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        static string str = "server=.;database=shuDB;uid=sa;pwd=accp";
        SqlConnection conn = new SqlConnection(str);
        DataSet set = new DataSet();
        SqlDataAdapter adapter;

        int index = 0;  //sql语句中的索引
        int yeshu = 1;  //下一页显示的页数
        int sum = 0;   //总页码

        //加载前6行数据
        private void Form1_Load(object sender, EventArgs e)
        {
            this.label1.Text = "" + yeshu.ToString() + "";
            string sql = @"select top 6 * from shu s";
            GetDataSet(sql);

            string sql2 = @"select MAX(shuid)/6 from shu";
            conn.Open();
            SqlCommand comm = new SqlCommand(sql2,conn);
            sum =(int)comm.ExecuteScalar();
             if (sum == 0) { return; }
             this.label2.Text = "总页数" + sum.ToString();
             conn.Close();
        }

        //上一页
        private void button1_Click(object sender, EventArgs e)
        {
            if (index == 0 || yeshu == 0) { return; }  //页数是0则返回
            index--;
            yeshu--;
            this.label1.Text = "" + yeshu.ToString() + "";
            string sql = @"select top 6 * from shu where shuid not in
                (select top (6*" + index + ") shuid from shu)";
            GetDataSet(sql);

        }

        //下一页
        private void button2_Click(object sender, EventArgs e)
        {
            if (yeshu==sum)  //如果翻的页数等于总页数
            {
                MessageBox.Show("已经是最后一页!");
                return;
            }        
            index++;
            yeshu++;
            this.label1.Text = "" + yeshu.ToString()+"";
            string sql = @"select top 6 * from shu where shuid not in
                (select top (6*"+index+") shuid from shu)";
            GetDataSet(sql);
        }

        //绑定
        public void GetDataSet(string sql)
        {
            adapter = new SqlDataAdapter(sql, conn);
            if (set.Tables["stu"] != null)
            {
                set.Tables["stu"].Clear();
            }
            adapter.Fill(set, "stu");

            this.dataGridView1.DataSource = set.Tables["stu"];
        }
    }
}
View Code

 

转载于:https://www.cnblogs.com/LJSL/p/3496200.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值