jbabey
jbabey

Reputation: 46657

Nested user controls can't access Page context in Render

This question seems related to How to access page controls from user control?, but I do not believe it is a duplicate.

I have many user controls that need to access the Page variable during their Render events. This works fine when I drop the controls on a .aspx page. However, when I try to nest the controls like so:

Protected Overrides Sub Render(ByVal writer As HtmlTextWriter)
    Dim nestedControl = New CustomControl()

    helpIcon.RenderControl(writer)

    MyBase.Render(writer)
End Sub

I get an exception that Variable cannot be null: Page from the Render event of CustomControl (the control being nested).

Is there an easy way to fix this so that controls constructed in another control's code behind have access to the Page context?

Upvotes: 0

Views: 365

Answers (2)

Dustin Hodges
Dustin Hodges

Reputation: 4195

The only time I've seen a control's page property be null is when the control has not been added to a control collection: e.g.

Me.Controls.Add(helpIcon) //This must happen before calling render

You won't need to call the render method if the control is added to a rooted control collection

Upvotes: 1

matt-dot-net
matt-dot-net

Reputation: 4244

You need to add the control the page's control tree and then it will get rendered normally without having to call Render()

Page.Controls.Add(new CustomControl());

More likely you will add it to some container on the page:

PlaceHolder1.Controls.Add(new CustomControl());

Upvotes: 1

Related Questions