Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 783
Sergey Kovalev Avatar asked Sep 05 '09 16:09

Sergey Kovalev


Video Answer


1 Answers

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.
like image 133
patmortech Avatar answered Sep 18 '22 15:09

patmortech