OnInit / User Controls

B

Brandon Potter

Why is it that when I override the OnInit method for a page, I can add a
user control like this:

Me.Controls.Add(LoadControl("MyControl.ascx"))

(where MyControl.ascx is your every day user control)

.... but when I use:

Dim mC As New MyControl
Me.Controls.Add(mC)

.... it doesn't show up?

It works if use the generic Control type:

Dim mC As Control
mC = LoadControl("MyControl.ascx")
Me.Controls.Add(mC)

I thought ASP.NET would add user controls to a page just the same as
controls... am I missing something?

Brandon
 
T

Teemu Keiski

Hi,

it is the difference between code-behind and inline code and its impact what
you see here. Code-behind model in v1 and v1.1 involves two classes, the one
that is compiled dynamically (by page parser) and then the actual
code-behind class (which you develop with VS.NET). The dynamically created
class inherits from your code-behind class, that's the idea briefly.

Now when you instantiate the control like: Dim mC As New MyControl, you
instantiate the code-behind class but you don't cause parsing happen for the
ascx (which contains the markup). E.g you create control instance of the
code-behind class but not the dynamic class (which is created when ascx is
parsed) and the code-behind class lacks the markup which is in dynamic
class.

When you create the control instance with LoadControl, ascx is parsed and
the ascx file contains details about the relevant code-behind class (in
directive) and therefore the correct code-behind class is instantiated also.
 
S

Scott Allen

Hi Brandon:

Dim mC As New MyControl

Creates an object of type MyControl - which is the class "behind" the
ascx.

LoadControl("MyControl.ascx")

Goes through the additional steps needed to compile the ascx,
initialize it, automatically wire up event handlers if needed, etc.
etc.

The difference then isn't in how you declare the variable (MyControl
versus a plain Control), but how it's created (with New or with
LoadControl). The following should work if you need a variable of type
MyControl.

Dim mC As MyControl
mC = DirectCast(LoadControl("MyControl.ascx"), MyControl)
Me.Controls.Add(mC)

HTH,
 

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

Top