Question

I have a user control that uses the standard if(!IsPostBack){//initialize myself} paradigm to avoid re-doing initialization during postbacks (so, trading fewer DB hits for increased ViewState usage). That approach serves me well most of the time but there's one place where I want to add this control to the control hierarchy 'late', during a postback.

This, of course, causes the initialization logic to fail, and the control to be rendered in an uninitialized state.

What guard should I be using to determine whether I should initialize, since !IsPostBack isn't cutting it? I could set a flag during LoadViewState, but that seems a bit hackish. What I'd like to find is some condition that only happens when a control is first added to the control hierarchy, and key on that. Does such a condition exist?

[edit] Sample pseudocode follows for the containing page:

protected void Page_Prerender(object sender, EventArgs e)
{
    Controls.Add(LoadControl("some_control.ascx"));
}

Is there a way for some_control to know it's been added late?

Was it helpful?

Solution 4

Further searches did not lead me to a general solution to this problem. What I ended up doing was setting a flag in Page_LoadViewState which suppressed the control's initialization - effectively the same thing as guarding the initialization with !IsPostBack, but a bit more precise.

OTHER TIPS

Can't you use the constructor to initialize your child controls? (or create a Initialize method) Then you control when the control is initialized.

Maybe this will help you to understand your problem: “…what if a control is created in an event handler and dynamically added to the control tree? In that case, the control plays catch-up. As soon as it is added to the control tree, it starts to execute its phases until it reaches the current phase of the page…”

More informations here:

http://weblogs.asp.net/vga/archive/2003/08/11/23498.aspx

There isn't really a concept of adding a control for the "first" time, because remember that every single time you request a page, a new page object is created, with all new control instances. Previously created control instances aren't being added to your new page object.

Why does the initialization logic fail? Perhaps if you posted that code we could suggest something - it doesn't seem like that should necessarily have to be the case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top