R – Child Control Initialization in Custom Composite in ASP.NET

asp.netcontrolscustom-server-controls

Part of the series of controls I am working on obviously involves me lumping some of them together in to composites. I am rapidly starting to learn that this takes consideration (this is all new to me!) 🙂

I basically have a StyledWindow control, which is essentially a glorified Panel with ability to do other bits (like add borders etc).

Here is the code that instantiates the child controls within it. Up till this point it seems to have been working correctly with mundane static controls:

    protected override void CreateChildControls()
    {
        _panel = new Panel();

        if (_editable != null)
            _editable.InstantiateIn(_panel);

        _regions = new List<IAttributeAccessor>();
        _regions.Add(_panel);
    }

The problems came today when I tried nesting a more complex control within it. This control uses a reference to the page since it injects JavaScript in to make it a bit more snappy and responsive (the RegisterClientScriptBlock is the only reason I need the page ref).

Now, this was causing "object null" errors, but I localized this down to the render method, which was of course trying to call the method against the [null] Page object.

What's confusing me is that the control works fine as a standalone, but when placed in the StyledWindow it all goes horribly wrong!

So, it looks like I am missing something in either my StyledWindow or ChildControl. Any ideas?

Update

As Brad Wilson quite rightly pointed out, you do not see the controls being added to the Controls collection. This is what the _panel is for, this was there to handle that for me, basically then override Controls (I got this from a guide somewhere):

    Panel _panel;    // Sub-Control to store the "Content".
    public override ControlCollection Controls
    {
        get
        {
            EnsureChildControls();
            return _panel.Controls;
        }
    }

I hope that helps clarify things. Apologies.

Update Following Longhorn213's Answer

Right, I have been doing some playing with the control, placing one within the composite, and one outside. I then got the status of Page at event major event in the control Lifecycle and rendered it to the page.

The standalone is working fine and the page is inited as expected. However, the one nested in the Composite is different. It's OnLoad event is not being fired at all! So I am guessing Brad is probably right in that I am not setting up the control hierarchy correctly, can anyone offer some advice as to what I am missing? Is the Panel method not enough? (well, it obviously isn't is it?!) 😀

Thanks for your help guys, appreciated 🙂

Best Answer

I don't see you adding your controls to the Controls collection anywhere, which would explain why they can't access the Page (since they've never been officially placed on the page).

Related Topic