0
Answer

How to update Page.Header from User Control with Master/Content Page

Byron Caldwell

Byron Caldwell

16y
4.9k
1

I have a user control that injects a css file into the page header from its Page_Load event like this:

HtmlLink link2 = new HtmlLink();

link2.Href = Page.ResolveUrl("~/Controls/CSS/" + cssFileId + ".css");

link2.Attributes.Add("type", "text/css");link2.Attributes.Add("rel", "stylesheet");

Page.Header.Controls.Add(link2);

 This works fine on a stand alone aspx page.

When I try to add the control to a content page (that's using a MasterPage), I get the following error on the user controls Page.Header.Control.Add(link2) line:

The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases.

Can anyone tell me how to get this to work in a Master/Content page context? The PreInit event won't work because it isn't accessible in a user control. And I need the user control to add the css file as the selection of css file to use needs to be a design time decision.