How to load a usercontrol(ascx) that is referenced

2019-08-06 23:31发布

问题:

I have usercontrol in oneproject and i added the reference of it in another project which will have my aspx page. How to append the control in my page. I have come across we should use loadcontrol method with virtual path. But i am not getting anything about virtual path. Pls help me on this.

回答1:

If you want to load dynamically then you should use LoadControl

var c = this.LoadControl("~/AddressControl.ascx");
this.myPanel.Controls.Add(c);

If you do not want to load it dynamically, then you just need to specify the control in your markup as nay other user control:

<AddressControl runat="server" ID="myControl" />

The problem in your case is that you actually need a reference to the ASCX file under your web application or under a virtual directory.

You would have to copy your ASCX file to your application, you can do that step easy by configuring the post-build actions

Take a look at the following article which describes in detail how to accomplish this process:

http://webproject.scottgu.com/CSharp/UserControls/UserControls.aspx

This is like a workaround, because user controls are not designed to be shared across projects, the best control that would fit your situation are called server controls, they are designed for this purpose