I am working on a website that has many MasterPages and one of them inherits from another master page and I am trying to add a control to the parent masterpage like this
myMasterPage.Page.Controls.Add(new LiteralControl(theSuperStoreString.ToString()));
But I get the following error
The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases.
How can i do this?
Thank you
First of all you should never add any control to your parent control. It violates separation of concerns principle, breaks integrity and is the first sign of bad design (and troubles in the project).
If you have to modify Controls of your parent or another control use event, state property or interface to delegate this request to the object which is really responsible for it (parent MasterPage in that case).
Regarding to your question place a control in your parent MasterPage and show it only when someone request for it.
I think you are trying to add the control too late in the cycle, try the preinit event
added as I read your comment
here is a link to the lifecycle
http://msdn.microsoft.com/en-us/library/ms178472.aspx
so essentially what we are saying is you need to overrid ethe preinit event and add/create new controls there rather than the later events (where it seems you are currently trying to add)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.