UserControl type not available if code behind file isn't in app_code directory

I ran into a weird problem with dynamically created ASP.NET 2.0 user controls yesterday. I was using the user control to populate a panel of a tab control which meant I didn’t actually have a reference to the user control object anywhere on my form. The only way I could get a reference to it was by looking at the UserControl property of the tab that it was displaying in.

I’d given the user control a public property that I was using to pass data between the user control and the main page and I wanted to cast the object I got back into the type that I’d created in my user control’s code behind. The problem was that when I tried to cast it the compiler didn’t know about the type that I’d created in code behind and when I looked at the type of the object I was getting it was something weird like ASP.relative_path_usercontrol_aspx.

I eventually figured out that if I moved the user control’s code behind into the App_Code directory my user control suddenly had the type I was expecting at runtime.

The really annoying thing that was I couldn’t actually have my code behind file in the App_Code directory and have the .ascx file linked to the code behind using the CodeFile property. As soon as I linked the two files together I got the following error:
The file ‘/Project/App_Code/MyUserControl.ascx.cs’ is in the special directory ‘App_Code’, which is not allowed

This is annoying because it means that my user control misses out on some of the dynamic class generation stuff that happens in ASP.NET 2.0 and I had to manually add the controls to the top of the user control like we had to in ASP.NET 1.x:

public partial class MyUserControl : System.Web.UI.UserControl
{
   protected Label Label1;
   protected Image Image1;
   protected Label Label2;
   ...
}

I did a bit more searching about the problem and came across a very interesting post about changes to the way pages are compiled in ASP.NET 2.0.

Posted on 06 Apr 06 by Helen Emerson (last updated on 06 Apr 06).
Filed under ASP.NET, Javascript, Server controls