2
votes

I'm trying to add a custom user control to a Panel in a visual web part in Sharepoint 2010, with the following lines of code:

MyUserControl userControl = new MyUserControl();

MainContentPanel.Controls.Add(userControl);

However, my user control fails to load/render. The above code is triggered by clicking a link button.

Am I missing something, or is it just not possible to do it this way?

2

2 Answers

3
votes

Because the usercontrols are stored in the 12/14 hive you need a clear reference to the path of the user control. Thats why you always need to do:

private const string _ascxPath = @"~/_CONTROLTEMPLATES/ProjectFolder/controlname.ascx"; 

MyControl MyUserControl = (MyControl)LoadControl(_ascxPath);

Controls.Add(MyUserControl);

However, you can also add it directly to the webpart/page/control by doing something like (determined by where you're placing it):

<%@ Register TagPrefix="MyPrefix" Namespace="MyNameSpace.MyControl"
    Assembly="MyAssemby"%>

 <MyPrefix:MyControl ID="MyId" runat="server" />