天天看点

用DataPager与ListView实现分页。

主要是用 PageDateSource类实现分页控制,但DataList不可以与其配合。

前台代码如下:

<div>

            <asp:ListView runat="server" ID="lv">

                <ItemTemplate>

                    <table>

                        <tr>

                            <td><%#Eval("id")%></td>

                            <td style="width: 300px"><a href="javascript:" target="_blank" rel="external nofollow" ><%#Eval("content") %></a> </td>

                        </tr>

                    </table>

                </ItemTemplate>

            </asp:ListView>

            <asp:DataPager runat="server" PagedControlID="lv" PageSize="4" ID="pd" OnPreRender="pd_PreRender">

                <Fields>

                    <asp:NextPreviousPagerField ShowFirstPageButton="True" ShowNextPageButton="False" ShowPreviousPageButton="False" />

                    <asp:NextPreviousPagerField ShowPreviousPageButton="False" />

                    <asp:TemplatePagerField>

                    </asp:TemplatePagerField>

                    <asp:NumericPagerField ButtonCount="3" />

                    <asp:NextPreviousPagerField ShowNextPageButton="False" />

                    <asp:NextPreviousPagerField ShowLastPageButton="True" ShowNextPageButton="False" ShowPreviousPageButton="False" />

                </Fields>

            </asp:DataPager>

        </div>       

后台代码跟常见的数据源绑定基本一样,但需要注意的一点是数据绑定事件要写在 Datapager的PreRender事件中,否则会出现下一页等需要点击两下的情况如下:

 void databind()

        {

            List<Notice> datas = new List<Notice>();           

            for (int i = 0; i < 100; i++)

            {

                Notice n = new Notice();

                n.id = i.ToString();

                n.content = string.Format("第{0}条通知",i);

                datas.Add(n);

            }          

            lv.DataSource = datas;

            lv.DataBind();

        }

        protected void pd_PreRender(object sender, EventArgs e)

        {

            databind();

        }

 public class Notice

    {

        public string id { get; set; }

        public string content { get; set; }

    }

程序运行截图如下:

用DataPager与ListView实现分页。