Create SharePoint 2013 web part that loads user controls

1.6k views Asked by At

I need to create a web part that loads users controls into it. All the answers I found are either outdated or not working.

I'm using visual studio 2015 and SharePoint 2013. I created a project with my user control and other with the web part, but I don't know how to link them...

Any help? Thanks

1

There are 1 answers

9
Cecilia On BEST ANSWER

If your webpart is not a Visual webpart, you can load user controls like this (in the webpart cs file):

namespace ProjectName.Folder.Custom_Webpart
{
    [ToolboxItemAttribute(false)]
    public class Custom_Webpart : System.Web.UI.WebControls.WebParts.WebPart
    {
        private const string _ascxPath = @"~/_CONTROLTEMPLATES/15/ProjectName/Folder/Custom_UserControl.ascx";

        protected override void CreateChildControls()
        {
            var control = Page.LoadControl(_ascxPath) as Custom_UserControl;
            //this.ChromeType = PartChromeType.None;
            Controls.Add(control);
        }
    }
}

If your webpart is a Visual webpart, you can load user controls inserting the following instructions in your webpart .ascx file:

<%@ Register Src="/_controltemplates/15/ProjectName/Folder/Custom_UserControl.ascx" TagPrefix="Custom" TagName="CustomControl" %>

<Custom:CustomControl runat="server" />