ASP.NET DataPager not paging after first PostBack?

A few posts ago, I mentioned that I am currently giving a classroom training on ASP.NET. People attending are currently working on a project I gave them, and today one of them came up to me with a strange problem...

Here's the situation: in VS 2008, a web page was created containing 2 controls: a DataList and a DataPager. This DataPager serves as the paging control for the DataList. Databinding is done in the codebehind:

[code:c#]

protected void Page_Load(object sender, EventArgs e) {
    ListView1.DataSource = NorthwindDataSource;
    ListView1.DataBind();
}

[/code]

This works perfectly! When the page is rendered in a brwoser window, data is shown in the DataList control. Now, when testing the DataPager, something strange happens: when a page number is clicked, ASP.NET will process a PostBack, rendering... the same page as before! Clicking the DataPager again is the only way to really go to a different page in the result set.

Let's have a look at the ASP.NET page lifecycle... The page Load event is actually not the best place to call the DataBind() method. PreRender is a better place to call DataBind():

[code:c#]

protected void Page_Load(object sender, EventArgs e) {
    ListView1.DataSource = NorthwindDataSource;
}

protected void Page_Render(object sender, EventArgs e) {
    ListView1.DataBind();
}

[/code]

kick it on DotNetKicks.com

This is an imported post. It was imported from my old blog using an automated tool and may contain formatting errors and/or broken images.

Leave a Comment

avatar

4 responses

  1. Avatar for Brad
    Brad February 6th, 2008

    What if you need to doing your databind after several methods in the page load have already run.

    There has to be a fix for this somehow...

  2. Avatar for maartenba
    maartenba February 6th, 2008

    This is simply due to the ASP.NET page lifecycle... Of course you can work around this, but I fear that might lead to frustration.

  3. Avatar for brad
    brad February 9th, 2008

    How can you work around this?

  4. Avatar for Jonathan
    Jonathan February 15th, 2009

    check the end of this page, I found the solution there
    http://nayyeri.net/blog/usi...
    if you have problems to see it, here is the solution:

    aspx:
    <asp:ListView runat="server" ID="rptProds" OnPagePropertiesChanging="listItems_PagePropertiesChanging">

    code behind:
    protected void listItems_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e) {

    this.pagingProds.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);

    BindYourDataAgain();

    }