Add user control to web part in Sharepoint 2013

22,284

You forgot to try one more option. It's the same when accessing the _layouts folder. You should specify the 15 hive.

The correct path is "~/_ControlTemplates/15

 NewsLine newsLine = Page.LoadControl(@"~/_ControlTemplates/15/MainTheme/NewsLine.ascx") 
Share:
22,284

Related videos on Youtube

4tuneTeller
Author by

4tuneTeller

Updated on July 09, 2022

Comments

  • 4tuneTeller
    4tuneTeller almost 2 years

    I've got a visual web part (created with standart Visual Stuido 2012 template from "Add new item" form) with just a single <div id="newsListDiv" runat="server"></div> element. I want to programmatically add my own user control to it using the following code:

    protected void Page_Load(object sender, EventArgs e)
    {    
        NewsLine newsLine = Page.LoadControl(@"~/_ControlTemplates/MainTheme/NewsLine.ascx") as NewsLine;
        newsListDiv.Controls.Add(newsLine);
    }
    

    But when I deploy the solution and add the web part to the page it shows an error page, telling me that the file '/_ControlTemplates/MainTheme/NewsLine.ascx' does not exist. But if I look into folder "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\TEMPLATE\CONTROLTEMPLATES\MainTheme" I can see that the file is present there. I've tried to set the trust level to "Full" but got the same error. I also tried adding the user control in .ascx file like this:

    <%@ Register Src="~/_controltemplates/MainTheme/NewsLine.ascx" TagPrefix="uc1" TagName="NewsLine" %>
    
    <div id="newsListDiv" runat="server">
        <uc1:NewsLine runat="server" id="NewsLine" />
    </div>
    

    And that way a get a compilation error: "The name 'InitializeControl' does not exist in the current context". I've also noticed, that as soon as I add Register or Reference line (with the path to my user control) to my .ascx file, the .g.cs file becomes blank! And it fills up again when I remove that line. I tried many different path writings like "../_controltemplates/", "/controltemplates/15/", etc. But none of them made any difference. I'm getting desperate here, please help!

  • 4tuneTeller
    4tuneTeller over 11 years
    Tried that one too, still no luck. It seems to me that there's some problem with the tool that automatically generate .g.cs file. Tried to re-install VS, but that didn't help either. I decided not to use UserControls for now, but I got an idea that it might not work because of I created ControlTemplates folder in the VS not as a mapped folder. Gonna check on that later...
  • Zakos
    Zakos almost 10 years
    this helped me for 2010->2013 upgrade on "bla-bla.ascx" file was not found issue