ASP.Net User Control ‘does not exist in the current context’

I may be missing something, but a search around the Internet revealed several people having the same problem and not finding any good answers.  You have an ASP.Net user control with fields on it, but when you compile you get an error.  Intellisence knows the objects are there, but the compiler doesn’t.  What do you do?

Like I said, I might be wrong – but after a lot of trial and error, and error, and error I settled upon this fix.  The error comes from the fact that the .ascx.cs file is compiled before the .ascx page.  So, if could could compile them separately it will actually work (I know, I managed to accomplish this by accident).

What does not work is to declare the form controls as protected variables in the code behind.  If you set them in place in the .ascx file, then they have already been declared and initialized.  However, if you did not place them in .ascx page, you could add them programatically at run time from the code behind and that would work – it’s not pretty, and to be avoided if you can, but it will work (assuming you know when you’re developing this control that the layout of the form controls is static, if its dynamic then please add them programatically).  I also tried data binding, which is likely the official solution – but I ran into problems along that route as well.

If you’re altering an .aspx page, make sure to change to <%@ Page directive to a <%@ Control directive, such as:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="myControl.ascx.cs" Inheirits="myControl" %>

What I then did was to add string fields to hold my values as protected members in the code behind:

#region form strings
protected String firstName = "";
protected String lastName = "";
protected String phoneNumber = "";
protected String emailAddress = "";

The function that did pull the contents from the form variables, formerly called btnSubmit_Click(),  instead uses the holder variables and is now called processForm().  The submit event handler is then created in the .ascx file directly:

<script language="cs" runat="server">
    protected void btnSubmit_Click(object sender, EventArgs e)
        this.firstName = txtfName.Text;
        this.lastName = txtLname.Text;
        this.phoneNumber = txtPhone.Text;
        this.emailAddress = txtEmail.Text;


There you have it.  Maybe not the most elegant, but when you’re hitting your head on the wall, this will save you.

Comments are closed.