Search code examples
c#asp.netwebusercontrol

Cannot reference my web usercontrol (ascx) from code behind


I am trying to dynamically create a user controls in Visual Studio 2012/ASP.Net/C# but my project does not recognise the type name of my user control when I try to use it in the code behind of any other aspx or ascx page. I've tried rebuilding it and also removing namespaces and it seems like it should just work but it doesn't!

The top line of my ascx file is this:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="AG_Controls_WebUserControl" %>

The corresponding codebehind looks like this:

public partial class AG_Controls_WebUserControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

I try to declare in instance of it in the code behind of a blank aspx page like this:

AG_Controls_WebUserControl test = new AG_Controls_WebUserControl();

And I just get :

Error 3 The type or namespace name 'AG_Controls_WebUserControl' could not be found (are you missing a using directive or an assembly reference?)

It's been a long day and I am pretty tired but this shouldn't be rocket science, but I can't see what the problem is. Help much appreciated!


Solution

  • You forgot to include the reference to the control in the ASPX page. You still need to include that reference if you are dynamically creating the control in the code behind.

    <%@ Register src="WebUserControl.ascx" tagname="WebUserControl" tagprefix="uc1" %>