private vs protected declaration of User Controls

G

Guest

Hello,

When I add a User Control to a web form and then try to declare it in the
code as a private member it doesn't get instantiated. However with
'protected' it's OK!

For example I get a runtime error on the line indicated in
InitializeComponent() because the user control is null. However if I declare
it as 'protected' it's ok.

private myUserControl userControl;
....
InitializeComponent()
{
....
userControl.Click += new EventHandler(userControl_Click);
}
 
M

Marina

That is because the .aspx is turned into a class that actually inherits from
the class in your .vb file. The .aspx contains the declaration of your
control. The name you give it there, needs to match up to a variable in the
class. Now, if this variable is declared as private, the .aspx class cannot
see it - and thus there is a disconnect there, and the object does not get
instantiated. If it is protected, the then .aspx class can see it (because
it inherits from the .vb class), and it is matched up to the object declared
in the .aspx itself.
 
T

Teemu Keiski

Hi,

it is due to the code model of asp.net so that it involves two classes, one
being the one you code (the code-behind class) and the other being one
generated dynamically when the markup is parsed (ascx, aspx etc). This class
created dynamically from markup inherits from your code-behind class and
therefore for members to be visible through the classes (and so that they
can be set to point to the controls), members must be at least protected.

In ASP.NET v2 this has changed due to partial classes so that no member
declarations for controls are needed.
 

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,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top