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

时间:2022-08-25 23:24:03

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.

我有一个用户控件,我已经编写并添加到ASP.NET页面,并且运行正常。但是,我试图在Page_Load上的代码后面引用该自定义控件中的属性,但不能,因为该实例的可访问变量为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.

用户控件和Page_Load这是正常的吗?如果是这样,我如何引用控件的实例以访问其公共属性?这是我在呈现页面之前需要做的事情,以便初始化一些变量。

2 个解决方案

#1


0  

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

您可以从Page_PreRender事件访问您的用户控件。

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

您可以在此处找到有关页面生命周期的更多文档。

#2


15  

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

唯一的区别是直接引用ascx文件而不是程序集中的控件。去搞清楚!?

#1


0  

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

您可以从Page_PreRender事件访问您的用户控件。

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

您可以在此处找到有关页面生命周期的更多文档。

#2


15  

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

唯一的区别是直接引用ascx文件而不是程序集中的控件。去搞清楚!?