开发者

In ASP.Net, why can't I access a server control's properties from the ASPX page's constructor?

开发者 https://www.devze.com 2023-01-19 04:18 出处:网络
In object-oriented languages, if class A contains class B as a member, you can access c开发者_JAVA技巧lass B\'s properties from class A\'s constructor (after you instantiate class B first).

In object-oriented languages, if class A contains class B as a member, you can access c开发者_JAVA技巧lass B's properties from class A's constructor (after you instantiate class B first).

However in ASP.Net, my understanding is that a Page object contains server control objects as its members, but I do not understand why, if you try to access a server control's properties from the Page constructor, you get a NullReferenceException.


It sounds more like a Life Cycle problem. The controls contained on your page is not created at the same time as your Page object, but later in the cycle of your httprequest.

This page gives a clear picture of the cycle: http://msdn.microsoft.com/en-us/library/ms178472.aspx.

You should instead override the Init-method to be sure your controls are initialized. Quote from the article

Raised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Init event of the page. Use this event to read or initialize control properties.


In the constructor, the ASPX has not run yet, so all of the server-side controls are null.

Move your code to Page_Load.

0

精彩评论

暂无评论...
验证码 换一张
取 消