Insights and discoveries
from deep in the weeds
Outsharked

Tuesday, January 4, 2011

Null References to UserControl Member Controls

[Note: This post is from an archive of "Stupid Problems with Easy but Hard To Find Solutions" that I've created over the years. These are those small, yet annoying problems that come up once in a while, but for some reason you can't remember what the solution was, and the problem is sometimes general enough that it's impossible to find a solution with google.]


Why does this seem to happen all the time?

You have a UserControl. You include it in a page, either through markup or through code using Page.LoadControl(). You try to access a member of the partial class that’s in the ascx file and you get a null reference.

There are several reasons.

1) You added the control in code by instantiating a new class. This does not work for partial classes. You have to use Page.LoadControl(). I suppose there must be some logic for the compiler allowing this in the first place, but I can’t think of any.
2) You did not register the control specifically. Suppose in your web.config you have a directive such as:

<add tagPrefix="CustomControls" namespace="MyApp.WebControls" assembly="MyApp"/>

This will show everything in the MyApp.WebControls namespace in the markup for any page in your application. This is convenient and great for WebControls that do are complete classes, and have no ascx file that must be loaded. However, it will also lull you into believing that you can include UserControls the same way.
You cannot. Though available in the VS designer, it will not include the markup part of your UserControl when compiling. You need to register them specifically, either in the page markup or in web.config, for the whole class to be loaded.

In web.config,

<add tagPrefix="CustomControls" src="~/WebControls/MyUserControl.ascx" tagName="MyApp"/>

or in the page:

<%@ Register tagPrefix="CustomControls" src="~/WebControls/MyUserControl.ascx" tagName="MyApp" %>