ASP.NET User Control instance is null when referen

2020-07-11 05:23发布

问题:

I have a user control that I have written and have added to an ASP.NET page, and functions just fine. However, I am trying to reference a property in the that custom control from code behind, on Page_Load, but cannot, because the variable, which is accessible, for the instance is null.

Is this normal for user controls and Page_Load? And if so, how can I make a reference to the control's instance in order to access its public properties? This is something I need to do before the page is rendered, in order to initialize some variables.

回答1:

You can probably access your user control from the Page_PreRender event.

You can find more documentation about the page life cycle in asp.net here.



回答2:

I had the same issue, and it turned out that I was registering my custom control incorrectly.

Correct Definition:

<%@ Register Src="PeriodControl.ascx" TagName="PeriodControl" TagPrefix="ucs" %>

Incorrect Definition:

<%@ Register TagPrefix="ucs" Namespace="MyWebsite" Assembly="MyWebsite" %>

The only difference was to reference the ascx file directly instead of the control in the assembly. Go figure!?