Question

Ok this is a really annoying bug that I have been having issues with all morning!.

I have a custom control that we have used on many project that has properties that are set and stored in Viewstate by the calling pages onload. the control sets up childcontrols with propertes on the CreateChildControls() method of the custom control.

Normally as usual on a postback the Page_Load event is fired then the CreateChildControls method of the control on the page is fired.

The strange thin though is we have a login system (custom membership provider) on the site and when a user is logged in the opposite happens first the CreateChildControls() method fires then the Page_Load so the control properties are wrong (set from the previous postback)

How could the events be firing in a different order? I thought all page events happened in the same order no matter what and I don't see how being logged in would change that order.

UPDATE: It seems the issue is I'm not calling EnsureChildControls() but I'm not sure where it should be called? If several properies are set on the control which are used in setting up the child controls when should I call EnsureChildControls(), I guess I don't fully understand what EnsureChildControls() does?

Was it helpful?

Solution

CreateChildControls is called whenever the ASP.NET page needs them. There is no specific point in the page cycle for that. It can happen in the Init event, it can happen in the Load event. If you want to make sure your child controls are available, then call EnsureChildControls() method of your control. You can do that in the control's Init event to make sure you have child controls through the whole lifecycle or you can do it whenever you need a reference to one of the child controls - e.g. in the getter/setter of a property of your control.

OTHER TIPS

When creating properties of a server/user control that need access to contained child controls I use the following:

public Whatever SomeProperty
{

    get
    {
        EnsureChildControls();
        <more code here>
    }
    set
    {
        EnsureChildControls();
        <more code here>
    }
}

This ensures your control consumers are free to work with your control at various stages of the page lifecycle.

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