Search code examples
asp.netsharepointuser-controlsweb-parts

Custom control does not exist exception in SharePoint


I'm trying to add a custom web UserControl to my SharePoint application. I have added my UserControl to a SharePoint WebPart and now i'm trying to load that WebPart in my page.

But when i add the WebPart i get the following exception:

The file /usercontrols/Test3Report.ascx does not exist.

But i'm 100% sure that both the file and folder exists. The path to the usercontrol also seems fine to me. This is how i try to load my control:

protected string UserControlPath = @"~/usercontrols/";
protected string UserControlName = @"Test3Report.ascx";

private Test3Report mycontrol;

protected override void CreateChildControls()
{
    try
    {
        mycontrol = (Test3Report)this.Page.LoadControl(UserControlPath + UserControlName);
        Controls.Add(mycontrol);
    }
    catch (Exception CreateChildControls_Exception)
    {
        exceptions += "CreateChildControls_Exception: " + CreateChildControls_Exception.Message;
    }
    finally
    {
        base.CreateChildControls();
    }
}

This seems right to me. I have no idea why it is complaining that i cannot find the Test3Report.ascx.

I've read something about the TrustLevel not set to full or something. Could that be it? Or any other ideas?


Solution

  • Try adding your new custom control by right-clicking on your solution in solution explorer in VS2010 -> add -> new item , after choosing sharepoint2010 from the list on the right, choose "User control". This way your control will be automatically created and later deployed in the mapped "~/_ControlTemplates/PROJECTNAME/UserControlNAME.ascx" folder which can be referenced to later.

    Also make sure that the user control is included in the package by opening the ".package" file in "Package" folder under solution explorer and checking that the user control is listed under "Items in Package".

    Tip: If possible for your use-case, instead of adding the custom control programmatically in CreateChildControls() you can put your destination page in design mode and then add your custom control by dragging and dropping the .ascx file from the solution explorer into you page.