c#在winform中用DataGridView实现分页效果

c#在winform中用DataGridView实现分页效果

public partial class Form11 : Form

{
public Form11()
{

InitializeComponent();
}

private int Inum = 1;
//行号,规定其索引初始值为1
int pagesize = 4;
int allCount
=0;
int pagecount = 0;

private void
Form11_Load(object sender, EventArgs e)
{

using(SqlConnection connection = new
SqlConnection("server=数服务器名称;uid=sa;pwd=sa;database=数据库名"))

{

SqlDataAdapter da = new SqlDataAdapter("select * from
tb_Land", connection);

DataTable dt = new DataTable();

da.Fill(dt);

allCount = dt.Rows.Count;
//获取数据表中记录的个数

pagecount = allCount %
pagesize; //页数 = 总数/显示的行数

//只能显示一页,判断是否是整除
if (pagecount == 0)

{
pagecount =allCount / pagesize;

}
else
{
pagecount
= allCount / pagesize + 1;
}

this.label1.Text = "共" +
pagecount.ToString() + "页";

show(1,4);
//分页显示记录

// this.label2.Text = "当前第" + Inum.ToString() +
"页";
}
}

/// <summary>
///
分页显示数据表中的信息
/// </summary>
/// <param
name="start"></param>
/// <param
name="end"></param>
private void show(int start,int
end)
{
SqlConnection connection = new
SqlConnection("server=服务器名称;uid=sa;pwd=sa;database=数据库名称");

SqlDataAdapter das = new
SqlDataAdapter("select top "+pagesize+" * from
tb_Land where Id not in (select top "+pagesize*(Inum-1)+" Id from

tb_Land)",connection);
//sql语句

DataSet ds = new DataSet();

//显示指定范围的记录

das.Fill(ds,"one");

this.dataGridView1.DataSource =
ds.Tables["one"].DefaultView; //绑定显示数据
ds =
null;
}

//第一页
private void
linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs
e)
{
Inum = 1;
show(Inum,
pagesize);
}

//末尾页
private void
linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs
e)
{
Inum = pagecount;
show(Inum-1,
pagesize);
}

//下一页
private void
linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs
e)
{
Inum++;
if (Inum <= pagesize)
//如果没有超出记录行数
{
show(Inum,
pagesize);
}
else

{
MessageBox.Show("现已是最后一页记录");
Inum =
pagecount-1; 更改为 Inum = pagecount;
return;
}

}

//上一页
private void
linkLabel4_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)

{
Inum--;
if (Inum >
0) //如果当前不是首记录
{

show(Inum, pagesize); //显示上一页记录
}

else
{

MessageBox.Show("现已是第一页记录");
Inum =
1;

return;

}
}

}
}

上一篇:WinForm DataGridView分页功能


下一篇:java原子操作