views:

342

answers:

3

uitest.ascx usercontrol events dont fire, does anyone have a clue about it?

        business.Pages.Page page1 = new business.Pages.Page();            

        System.Web.UI.HtmlControls.HtmlForm form = 
              new System.Web.UI.HtmlControls.HtmlForm();
        UserControl uc = 
              (UserControl)page1.LoadControl("~/usercontrols/uitest.ascx");            

        form.Controls.Add(uc);

        page1.Controls.Add(form);

        StringBuilder sb = new StringBuilder();
        StringWriter tw = new StringWriter(sb);
        HtmlTextWriter hw = new HtmlTextWriter(tw);

        page1.RenderControl(hw);            

        context.Response.Write(newContent);
+1  A: 

If this code is running in a custom HttpHandler (as I'm assuming from the question title), then this approach is not going to work.

The Page class is what implements the ASP.Net Page lifecycle. It is an implementation of IHttpHandler. The ProcessRequest() method of the Page object fires off the page lifecycle - FrameworkInitialize(), Init()... all the way through to OnLoadComplete(), OnSaveStateComplete().

Constructing a page object by calling it's constructor does not invoke the page lifecycle.

womp
+1  A: 

Let's step through what has happened here. You've created an instance business.Pages.Page, which means the page class' constructor is invoked. Then you've added a control to the Controls collection. Then you've called the RenderControl() method on that page.

Nowhere in that process have you initiated a request lifecycle for the page. How can the page's OnInit, OnLoad, etc ever fire if you don't invoke some method that fires them? During a normal page load, the page is the HttpHandler and the request pipeline kicks off each event, which in turn cascades through the page's control tree, firing on each child control.

Internally, this is done by calling System.Web.UI.Page.ProcessRequest(), which you could probably call via reflection but may have some unpredictable results.

The key to remember here is that these page and user control classes aren't special - they work the same as any other class. If you new() them up, the constructor fires. If you call RenderControl(), that method fires. Nothing more to it than that!

Rex M
A: 

See this answer to a similar question.

rick schott