why Page.LoadControl?

A

alecyy

hi,

I create a UserControl called "RegInfo.ascx",
then i add a PlaceHolder to WebForm1,
and in WebForm1.Page_Load() i wrote the follow statement:
placeHolder.Controls.Add(new RegInfo());
but when i pressed F5 to run the web app, it shows nothing. :(

after search web to find out solution, i replaced upper statement with:
placeHolder.Controls.Add(Page.LoadControl("RegInfo.ascx"));
it work as my expect!

I am so confused about the two results,
Don't they add a new instance of RegInfo into the placeHolder?
Why one can work exactly while anthor don't?
 
K

Karl Seguin

When you load a control, you do more than instantiate it..

new RegInfo();, as you know, creates a new instance of a class.

Page.LoadControl also creates a new instance, but also does a lot
more...such as bringing the control up to the same event life cycle. AS you
can imagine, if new did this, it would be inconsitent with how new works for
normal classes (simply calling the constructor...).

Cheers,
Karl
 
B

Bruce Barker

when you do new RegInfo() you are only creating an instance of the code
behind of your user control, which normally doesn't have any code to create
the controls it contains (these are usually on the aspx page that get
compiled). Page.LoadControl("RegInfo.ascx") creates an instance of the
actual user control (which inhertis from the code behind).

-- bruce (sqlwork.com)
 
A

alecyy

thx.
i got it.

Bruce Barker said:
when you do new RegInfo() you are only creating an instance of the code
behind of your user control, which normally doesn't have any code to create
the controls it contains (these are usually on the aspx page that get
compiled). Page.LoadControl("RegInfo.ascx") creates an instance of the
actual user control (which inhertis from the code behind).

-- bruce (sqlwork.com)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,133
Latest member
MDACVReview
Top