开发者

How to add a usercontrol dynamically without using <%@ register %> or <%@ Reference %>?

I have some usercontrol which gets loaded dynamicaly. I know how to add these usercontrols dynamically. The problem is, which usercontrol are to be added is decided only at runtime. So I cannot use <%@ register %> or <%@ Reference %> on the '.aspx' page.

开发者_运维技巧How to access the usercontrols without using these directives?


You can register all of your user controls within your web.config eliminating the need to register them at page level -- or needing to make a decision on which ones to register (at page level). e.g.

<pages>
  <controls>
    <add tagPrefix="myControl" src="~/Controls/uc.ascx" tagName="header"/>
 </controls>
</pages>

Check out this post by Scott Gu for additional help Tip/Trick Registering User Controls


Maybe this is what you mean, in Page_Load method:

var ctrl = LoadControl("yourcontrol.ascx"); Controls.Add(ctrl);


Can you not simply resister all usercontrols in your page (or even better in your web.config), and then this will not be an issue.


Regardless of where you register the control, it won't be automatically loaded on the page if you don't put a tag for it on the page.

To load the user control dynamically from code, you use the LoadControl method:

void Page_Init(object sender, System.EventArgs e)
{
    // Instantiate the UserControl object
    MyControl myControl1 =
        (MyControl)LoadControl("TempControl_Samples1.ascx.cs");
    PlaceHolder1.Controls.Add(myControl1);
}

Knowing that this is the method to use, you will be able to find plenty of examples. Here is one place to start.


Why don't you put them into panel or multiview and display accordingly. But you also need to register it into webconfig.


On the page's code-behind:

var ctrl = LoadControl("user.ascx");
this.Controls.Add(ctrl);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜