ASP.NET user control: Page_Load fires before property is set

Sergey Kovalev picture Sergey Kovalev · Sep 5, 2009 · Viewed 10.5k times · Source

This is driving me crazy.

I have a very simple user control:

public int? ImageId {set; get;}

protected void Page_Load(object sender, EventArgs e)
{
     ... do something with ImageId...
}

And then I put this control on the page with ListView within UpdatePanel:

<asp:ListView ID="ListViewImages"  runat="server" DataSourceID="src">
  <LayoutTemplate>
    <asp:PlaceHolder ID="itemPlaceholder" runat="server" />
  </LayoutTemplate>
  <ItemTemplate>
    <My:MyControl ImageId='<%# Eval("Id") %>' ID="cipPreview" runat="server"  />
  </ItemTemplate>
</asp:ListView>

The problem is Page_Load fires BEFORE ASP.NET sets ImageId. With debugger's help I found out that for some reason ImageId in MyControl IS SET, but it happens only after Page_Load has finished processing. What's wrong?

Answer

patmortech picture patmortech · Sep 5, 2009

It's probably because data binding on the ListView happens AFTER Page_Load fires, so therefore your property isn't set at that point. You could move your code to PreRender event since it is called after data binding is completed.

More info according to MSDN:

PreRender -- Before this event occurs:

  • The Page object calls EnsureChildControls for each control and for the page.
  • Each data bound control whose DataSourceID property is set calls its DataBind method.