2012-01-21 24 views
0

以下のようにWeb.configにusercontrolを登録します。 コードネームからヘッダーを含むusercontrolをプレースホルダに動的にロードするにはどうすればよいですか? I使用ASP.NET 4.0web.configの参照でUserControlをプログラムでロードする

<configuration> 
    <system.web> 
    <pages> 
     <controls> 
     <add tagPrefix="blogUc" src="~/Controls/Header/Header.ascx" tagName="header"/> 
     </controls> 
    </pages> 
    </system.web> 
</configuration> 

答えて

0

ここで良い記事How to Create Instances of ASP.Net UserControls Programmatically.は、ユーザーコントロールのコードビハインドファイルにではある名前空間への参照を置くことを忘れてはいけないです。

// Reference to namespace in Code-Behind file 
using MyNamespace.UserControls; 

// In code behind class 
protected MyUserControl userControl1 = null; 
0

web.configからページセクションをプログラムで読み込み、好きなコントロールを読み込むことができます。

参考:http://msdn.microsoft.com/en-us/library/system.web.configuration.tagprefixcollection.aspx

ここではあなたを助けるかもしれないコードです。 (あなたがコントロールの長いリストを持っている場合、パフォーマンスの問題である可能性があり、そのすべてのコントロールをループ集、ノート・)

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; 
    } 
} 
0

TemplateControl.ParseControlメソッドを呼び出し:

Control control = TemplateControl.ParseControl("<blogUc:header runat='server' />"); 
this.placeHolder.Controls.Add(control); 
関連する問題