views:

14

answers:

1

I don't think I understand fully how ASP.NET does inheritance of controls. I have a user control, ucBase, which has an asp.net label in the ascx file. Code behind references the label and it works fine during run time if the control is not a parent for another user parent.

If I have another user control, ucChild, inheriting from ucBase, the label in ucBase's code is always null. ucChild has no controls in its ascx file

The server controls (like the label) needs to be declared in the ascx file and not created programmatically.

What needs to be done for ucBase to see its own controls when it's a parent user control?

+1  A: 

The issue:

Inheritance only inherits the code part of your user control. Markup is not something that can be inherited, since it is dynamically compiled at runtime.

The relationship between the markup and your code-behind is done through the .designer.cs partial class that comes with your user control. This designer file contains declarations for all the objects in your markup. This basically decorates the code-behind class with a bunch of fields that are null object references - these will be initialized with actual instances when the compiled markup code is run.

When you inherit from the .ascx file, you are inheriting all these null object placeholders. However, since the markup in your new control is not the same as the parent control, none of those objects are actually created when the new control's markup doesn't contain the corresponding markup, and when it is parsed and compiled, all the references stay null. Does this make sense?

The fix:

The best way to do this is to make your user controls self contained, i.e. favor code-based composition rather than markup based. In other words, instead of using markup, set up your user control using Page_Init and adding all the controls you need to the Controls collection in code behind.

Then when you inherit this class, all the same code will be executed, ensuring that your child usercontrol has the same UI controls in it.

womp
I want the base user control to access its own controls on its own acsx file. This is NOT the case of a child user control trying to access a parent control. The base user control was a self contained control. When another user control inherits from it, the base user control doesn't work like a self contained user control anymore. There's a reason I mentioned I wanted the controls to be declared in the ascx file instead of being created programatically. So is there no way to make this work without programmatically creating the controls?
Tony_Henrich
That is correct, there is no way. .ASCX files are meant for small reusable chunks of content, and really aren't built to be distributed or inherited.
womp