Ashwin Singh
Ashwin Singh

Reputation: 7345

Difference between LoadControl and exposing a Constructor?

To add a usercontrol in codebehind there are two ways.

  1. Exposing a usercontrol constructor to the parent page.
  2. Using Page.LoadControl method.

So basically there are two different ways of doing the same task. Do one method work under certain circumstances and the other does not?What's the difference in how they work? and when to prefer one over the other?

Upvotes: 1

Views: 498

Answers (2)

Szymon Seliga
Szymon Seliga

Reputation: 820

I found the answer here

You need to understand the difference between Web Custom Controls and Web User Controls.

Web Custom Controls, like the WebControls (DataGrid, Button, ...) are classes. To create them you just call their constructor: Dim b as Button = new Button()

Web User Controls are defined by an ASCX page (containing HTML) and a class. The class is just the codebehind for the control, so if you call its constructor you don't create the control. That's where the LoadControl method is needed: you pass it the name of the ASCX page, and it loads both this page and the CodeBehind class.

Upvotes: 3

Chris Gessler
Chris Gessler

Reputation: 23113

LoadControl is primarily used to dynamically add a User Control to a page when the type is unavailable. Most user controls are unavailable in updatable website applications. Also note that because the type is unavailable, properties of the dynamically created user control are difficult to set.

MyControl c = new MyUserControl() is preferred, but doesn't stop you from doing something like:

MyControl c = (MyControl)Page.LoadControl('path to ascx');

However, I don't see the need.

Upvotes: 0

Related Questions