GridView自定义分页

本文介绍如何在ASP.NET中使用GridView控件实现分页功能,包括设置分页按钮、跳转页数输入框及相应的事件处理代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在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" />
            页次:&nbsp;<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;
        }
    }

 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值