GridView分页功能的实现

当GridView中显示的记录很多的时候,可以通过GridView的分页功能来分页显示这些记录。如果GridView是直接绑定数据库,则很简单:将"启动分页"打勾即可。

如果是用代码实现,则需要这么做:

1、允许分页AllowPaging属性为True;

2、设置GridView属性栏中PagerSetting里的一些属性中,定义分页的样式;

3、进行数据绑定,将数据显示到GridView上;

4、通过触发相关事件,将数据分页显示。

 

部分代码:

1.查询数据并绑定

 1 /// <summary>
 2 /// 查询数据进行数据绑定
 3 /// </summary>
 4 private void BindData()
 5 {
 6         //将数据部署到GridView中
 7          string Constr = "数据库信息";
 8         string sqlstr = "SQL语句";
 9         SqlConnection con = new SqlConnection(Constr);
10         SqlDataAdapter ad = new SqlDataAdapter(sqlstr, con);
11         DataSet ds = new DataSet();
12         ad.Fill(ds);
13         GridView1.DataSource = ds;
14         GridView1.DataBind();
15 }
View Code

2.事件处理

1 /// <summary>
2 /// 分页事件
3 /// </summary>
4 protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
5 {
6        GridView1.PageIndex = e.NewPageIndex;
7        //重新绑定数据
8         BindData();
9 }
View Code

3.添加分页显示

 1 /// <summary>
 2 /// 添加分页码显示
 3 /// </summary>
 4 protected void GridView1_DataBound(object sender, EventArgs e)
 5 {
 6     //添加分页码显示
 7     GridViewRow bottomPagerRow = GridView1.BottomPagerRow;
 8     Label bottomLabel = new Label();
 9     bottomLabel.Text = "目前所在分页:(" + (GridView1.PageIndex + 1) + "/" + GridView1.PageCount + "";
10     bottomPagerRow.Cells[0].Controls.Add(bottomLabel);
11 }
View Code

 

posted @ 2014-07-04 15:05  龍^o^少  阅读(1008)  评论(0编辑  收藏  举报