Reputation: 473
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?
Upvotes: 2
Views: 6330
Reputation: 922
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" />
Upvotes: 3
Reputation: 2017
I believe you need to use the LoadControl method. Also see How to: Create Instances of ASP.NET User Controls Programmatically
Upvotes: 2