在GridView里加上如下代码:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnDataBound="GridView1_DataBound" OnPageIndexChanging="GridView1_PageIndexChanging" AllowPaging="True" PageSize="15">
... ...
<PagerTemplate>
<asp:LinkButton ID="FirstButton" Text="首页" CommandName="Page" CommandArgument="First"
runat="Server" ForeColor="White" />
<asp:LinkButton ID="LinkButton1" Text="上一页" CommandName="Page" CommandArgument="Prev"
runat="Server" ForeColor="White" />
<asp:LinkButton ID="LinkButton2" Text="下一页" CommandName="Page" CommandArgument="Next"
runat="Server" ForeColor="White" />
<asp:LinkButton ID="LastButton" Text="末页" CommandName="Page" CommandArgument="Last"
runat="Server" ForeColor="White" />
<asp:TextBox ID="txtPageNum" runat="server" Width="30px"></asp:TextBox>
<asp:Button ID="btnGo" runat="server" Text="转到" OnClick="btnGo_Click" />
页次: <asp:Label ID="lblCurPage" runat="server" />/<asp:Label ID="lblTotalPage"
runat="server" />
</PagerTemplate>
</asp:GridView>
代码页加上如下的代码:
protected void GridView1_DataBound(object sender, EventArgs e)
{
GridViewRow pagerRow = GridView1.BottomPagerRow;
if (pagerRow == null) return;
Label curPage = (Label)(pagerRow.Cells[0].FindControl("lblCurPage"));
Label totalPage = (Label)(pagerRow.Cells[0].FindControl("lblTotalPage"));
TextBox txtPageNum = (TextBox)(pagerRow.Cells[0].FindControl("txtPageNum"));
int pn = GridView1.PageIndex + 1;
curPage.Text = pn.ToString();
totalPage.Text = GridView1.PageCount.ToString();
txtPageNum.Text = pn.ToString();
}
//如果是数据源是XXXDataSource类的就不用这个事件;如果是自定义的数据源就得加上这个。注意:得用DataTable、DataView才行,像DataReader是不可以的。
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex >= 0 ? e.NewPageIndex : 0;
GridView1.DataBind();
}
protected void btnGo_Click(object sender, EventArgs e)
{
GridViewRow pagerRow = GridView1.BottomPagerRow;
TextBox pageNum = (TextBox)(pagerRow.Cells[0].FindControl("txtPageNum"));
int pa = 0;
if (Int32.TryParse(pageNum.Text, out pa))
{
GridView1.PageIndex = pa - 1;
}
}