ross dickinson: web and desktop software developer

I discovered this bug/feature today. While working on a new page for work, I was having an issue where none of the child controls inside an ascx user control were instantiating during runtime, leading to all sorts of null reference exceptions. I wasn't quite sure why, as the custom control worked fine on every other page.

After a bit of tooling around, I found out that the problem was in how I registered the control at the top of the page. The problem was here:

<%@ Register Assembly="CompanyName" Namespace="CompanyName.Controls" TagPrefix="companyname" %>

I was trying to register the project's controls namespace so that I didn't have to register each control that I used individually. Visual Studio didn't complain, nor did the compiler. I was able to put in any of the types and it worked out fine. The big mystery is that, for reasons unknown to me, the user controls would instantiate on the page normally, but none of their child controls would. 

Switching the register back to

<%@ Register Src="~/Controls/UserControl.ascx" TagName="UserControl" TagPrefix="companyname" %>

And everything worked fine again.

The only thing I can figure out is that this is specific to user controls that have a designer file. External control libraries still work fine.


I finally realized why this was happening. Because the "ascx" part of a user control is a template, the template doesn't get loaded unless it's registered specifically. You can get around this by going: CustomControl.LoadTemplate("ascx path")!

About the author

rossisdead is a 26 year old web and desktop software developer from New Jersey. He has two cats and likes long walks on the beach.

On Stackoverflow

On Stackoverflow Careers

On Codeplex

On Github