Programmatically Modifying the HyperLinks in the DataPager control


As you know,the DataPager control can be used to Implement data paging in any data Control that implements the IPageableItemContainer interface.

For now,the only control that implements that interface(In .NET 3.5 sp1) is the ListView ASP.NET control.

By default the DataPager control will use the postback to pass the page index of the DataPager control.

However,the DataPager  can be configured to use the QueryString to pass the PageIndex for the Paged control, this can be done by setting it’s “QueryStringField” property to the name of the Query string field that you want.

Developers may use the QueryStringField option to when they want to :

  1. Implement outputCache for the ListView pages based on the QueryStringField,I explained this in this post.
  2. Implement a more user and SEO friendly Urls by using Url Rewriting.

You can implement Url Rewriting in by using the new Routing features which were introduced in ASP.NET 3.5. You can also use the tool if you like.

But when you will need to modify the Generated  Url in the page of DataPager control ?

  1. When you use Url Rewriting, you will need to modify the Urls of the Pager HyperLink controls in a way that can work with your Url Rewriting scheme.
  2. By default,the DataPager control will not include the SessionId in it’s HyperLinks when you use cookie less session mode.This of course will cause a session loss when you navigate through the ListView pages using the Pager
  3. Technorati Tags: ,
  4. links.You can fix that by using the Response.ApplyAppPathModifier function which will take the Url and correctly append the sessionId to it.

Modifying the HyperLink in the DataPager will only require to handle the ListView DataBound event and loop though the HyperLinks of the DataPager control:

 protected void ListView1_DataBound(object sender, EventArgs e)
        DataPager pager = ListView1.FindControl("DataPager1") as DataPager;
        // this check is important to avoid touching the Hyperlinks if the Pager doesn't configured to use Query string Field
        if (!string.IsNullOrEmpty( pager.QueryStringField))
            foreach (DataPagerFieldItem Pitem in pager.Controls)
                foreach (Control c in Pitem.Controls)
                    if (c is HyperLink)
                        HyperLink tmp = c as HyperLink;
                        tmp.NavigateUrl = "....";


Anas Ghanem.

1 Comment

  • Great One Anas, I was searching for this. But I have a problem that this only works when loading the ListView for the first time, after paging it stops working!
    For example when I click on page2 on the list view, the FindControl can't find the datapager

Comments have been disabled for this content.