简体   繁体   中英

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

In object-oriented languages, if class A contains class B as a member, you can access class 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM