ASP.NET User Control instance is null when referenced on Page_Load on page code behind

家住魔仙堡 提交于 2019-12-06 00:15:51

问题


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!?



来源:https://stackoverflow.com/questions/10340610/asp-net-user-control-instance-is-null-when-referenced-on-page-load-on-page-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!