I register usercontrols in Web.config as below. How do i dynamically load usercontrol with tagname header from code-behind into a placeholder? I Use ASP.NET 4.0
<configuration>
<system.web>
<pages>
<controls>
<add tagPrefix="blogUc" src="~/Controls/Header/Header.ascx" tagName="header"/>
</controls>
</pages>
</system.web>
</configuration>
Here is a good article How to Create Instances of ASP.Net UserControls Programmatically. do not forget to put a reference to the namespace that the UserControl is in in the code-behind file.
// Reference to namespace in Code-Behind file
using MyNamespace.UserControls;
// In code behind class
protected MyUserControl userControl1 = null;
You could programmatically read pages Section from web.config and load the controls you like.
Reference: http://msdn.microsoft.com/en-us/library/system.web.configuration.tagprefixcollection.aspx
Here is the code that might help you. (note- its looping through all Controls collections, which may be a performance problem if you have long list of controls)
PagesSection pagesSection = (PagesSection)WebConfigurationManager.GetWebApplicationSection("system.web/pages");
foreach (TagPrefixInfo tag in pagesSection.Controls)
{
if (tag.TagName == "header")
{
UserControl userControl= (UserControl) Page.LoadControl(tag.Source);
PlaceHolder1.Controls.Add(userControl);
break;
}
}
Call the TemplateControl.ParseControl
method:
Control control = TemplateControl.ParseControl("<blogUc:header runat='server' />");
this.placeHolder.Controls.Add(control);
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.