Search code examples
asp.net-2.0page-lifecycledynamic-controls

Dynamically adding controls from an Event after Page_Init


Might seem like a daft title as you shouldn't add dynamic controls after Page_Init if you want to maintain ViewState, but I couldn't think of a better way of explaining the problem.

I have a class similar to the following:

public class WebCustomForm : WebControl, IScriptControl
{
    internal CustomRender Content
    {
        get
        {
            object content = this.Page.Session[this.SESSION_CONTENT_TRACKER];
            return content as CustomRender;
        }
        private set
        {
            this.Page.Session[this.SESSION_CONTENT_TRACKER] = value;
        }
    }
}

CustomRender is an abstract class that implements ITemplate that I use to self-contain a CustomForms module I'm in the middle of writing.

On the Page_Init of the page that holds the WebCustomForm, I Initialise the control by passing the relevant Ids to it. Then on the overridden OnInit method of the WebCustomForm I call Instantiate on the CustomRender control that's currently active:

if (this.Content != null)
{
     this.Content.InstantiateIn(this);
}

The problem is that my CustomRender controls need the ability to change the CustomRender control of the WebCustomForm. But when the events that fire on the CustomRender fire, the Page_Init event has obviously already gone off. So, my question is, how can I change the content of the WebCustomForm from a dynamically added control within it?

The way I see it, I have three options:

  1. I separate the CustomRender controls out into their own stand alone control and basically have an aspx page per control and handle the events myself on the page (although I was hoping to just make a control I drop on the page and forget about)
  2. I don't use events and just keep requesting the current page, but with different Request Parameters
  3. I go back to the drawing board with any better suggestions anyone can give me.

Solution

  • I went with option 1. I did away with the overal control and just created separate controls that need to sit on different pages. I added properties to take Postback Urls and created Session properties for passing IDs between controls so I don't have to rely on RequestParams.