在 Gridview 分页上添加“上一页,下一页,共X页”等信息
原理比较简单,
就是利用GridView 在RowCreated事件上做个手脚,
当if (e.Row.RowType == DataControlRowType.Pager) 时
加入几个Button 和Label 之后再给他们写个事件就ok了
当然我觉得最有意思的就是最后的pager里面的对象嵌套。。。
拉出来一句
e.Row.Controls[0].Controls[0].Controls[0].Controls[0].Controls.AddAt(0, (Button_IndexFirst));
其中各个对象的含义,这里只做个参考给大家
Pannel对象->Table对象->TableRow对象->TableCell对象 恩 貌似是这样的。
雕虫小技,以博众高手一笑
以下是代码
//注意:GridView 必须开启分页功能,并启用RowCreated 事件
C#
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
#region 翻页绑定
if (e.Row.RowType == DataControlRowType.Pager)
{
Label label_Index = new Label();
LinkButton Button_IndexFirst = new LinkButton();
LinkButton Button_IndexLast = new LinkButton();
LinkButton Button_IndexNext = new LinkButton();
LinkButton Button_IndexPrevious = new LinkButton();
Button_IndexFirst.Text = "第一页 ";
Button_IndexFirst.CommandName = "first";
Button_IndexFirst.ForeColor = Color.White;
Button_IndexFirst.Click +=new EventHandler(PageButtonClick);
Button_IndexNext.Text = " 下一页 ";
Button_IndexNext.CommandName = "next";
Button_IndexNext.ForeColor = Color.White;
Button_IndexNext.Click += new EventHandler(PageButtonClick);
Button_IndexPrevious.Text = "前一页 ";
Button_IndexPrevious.CommandName = "previous";
Button_IndexPrevious.ForeColor = Color.White;
Button_IndexPrevious.Click += new EventHandler(PageButtonClick);
Button_IndexLast.Text = "最末页 ";
Button_IndexLast.CommandName = "last";
Button_IndexLast.ForeColor = Color.White;
Button_IndexLast.Click += new EventHandler(PageButtonClick);
label_Index.Text ="当前为第" + (GridView1.PageIndex + 1) + "页,共有"+((GridView)sender).PageCount+"页";
e.Row.Controls[0].Controls[0].Controls[0].Controls[0].Controls.AddAt(0, (Button_IndexFirst));
e.Row.Controls[0].Controls[0].Controls[0].Controls[0].Controls.AddAt(1, (Button_IndexPrevious));
int controlTmp = e.Row.Controls[0].Controls[0].Controls[0].Controls.Count-1;
e.Row.Controls[0].Controls[0].Controls[0].Controls[controlTmp].Controls.Add(Button_IndexNext);
e.Row.Controls[0].Controls[0].Controls[0].Controls[controlTmp].Controls.Add(Button_IndexLast);
e.Row.Controls[0].Controls[0].Controls[0].Controls[controlTmp].Controls.Add(label_Index);
//e.Row.Controls[0].Controls.Add(label_Index);
}
#endregion
}
protected void PageButtonClick(object sender, EventArgs e)
{
LinkButton clickedButton = ((LinkButton)sender);
if (clickedButton.CommandName == "first")
{
GridView1.PageIndex = 0;
}
else if (clickedButton.CommandName == "next")
{
if (GridView1.PageIndex < GridView1.PageCount - 1)
{
GridView1.PageIndex += 1;
}
}
else if (clickedButton.CommandName == "previous")
{
if (GridView1.PageIndex >= 1)
{
GridView1.PageIndex -= 1;
}
}
else if (clickedButton.CommandName == "last")
{
GridView1.PageIndex = GridView1.PageCount - 1;
}
}