Customize ASP.Net DataPager generated HTML

Donnie Thomas picture Donnie Thomas · Jun 12, 2009 · Viewed 11k times · Source

I am using a ListView and DataPager in my web project for pagination. It works fine, but the generated HTML for the pagination is simply a span containing some hyperlinks.

I wanted to customize the HTML and display the links in an unordered list instead (ul).

Anybody know how this can be done? One way I can think of is CSSFriendly adapters, but I don't want to do that if there is an easier way.

Edit: Could somebody help me out with the exact steps required to create the controls in the template? Sorry for being daft, but I can't figure this part out, in spite of extensive Googling.

Answer

Josh E picture Josh E · Jun 12, 2009

You can use the PagerTemplate to designate the markup you'd like to use for the paging control. I'm not sure exactly what you're trying to do in terms of displaying the paging information as as ul/li, but this should be enough to start you on the right track. Sorry for the code running long to the side...

ex:

<asp:DataPager ID="DataPager1" runat="server" PagedControlID="gridInvoiceHistory"
            PageSize="20">
            <Fields>
                <asp:TemplatePagerField>
                    <PagerTemplate>
                        Page
                        <asp:Label runat="server" ID="labelCurrentPage" Text="<%# Container.TotalRowCount > 0 ? (Container.StartRowIndex / Container.PageSize) + 1 : 0 %>" />
                        of
                        <asp:Label runat="server" ID="labelTotalPages" Text="<%#  Math.Ceiling ((double)Container.TotalRowCount / Container.PageSize) %>" />
                    </PagerTemplate>
                </asp:TemplatePagerField>

EDIT: here is a more detailed beginning to a solution for this:

<asp:TemplatePagerField>
     <PagerTemplate>
          <asp:BulletedList ID="listPages" runat="server" 
               DisplayMode="LinkButton" onclick="listPages_Click">
          </asp:BulletedList> 
     </PagerTemplate>
</asp:TemplatePagerField>

And here is what you would have in the code-behind:

protected void listPages_Click(object sender, BulletedListEventArgs e)
        {
            var pageNo = int.Parse((sender as BulletedList).Items[e.Index].Text);
            var startIndex = (pageNo - 1) * DataPager1.PageSize;
            DataPager1.SetPageProperties(startIndex, DataPager1.PageSize, true);
        }

What remains for you to do is to perform a databinding on the bulleted list against a method that gets the page count and returns an IEnumerable list of the text you want for the page links. Standard warning: this is sample code, and probably shouldn't be used in a production environment without a thorough vetting! :)