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 = ; //sql语句中的索引
int yeshu = ; //下一页显示的页数
int sum = ; //总页码 //加载前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 == ) { return; }
this.label2.Text = "总页数" + sum.ToString();
conn.Close();
} //上一页
private void button1_Click(object sender, EventArgs e)
{
if (index == || yeshu == ) { 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"];
}
}
}
上一篇:java中Scanner类nextInt之后用nextLine无法读取输入


下一篇:codevs3243 区间翻转