Problem creating web user control

C

Calvin Lai

Hi all,

I have a problem in creating web user control *programatically*. Problem as
follows:

1. WebUserControl1 contains a server side table named Table1
2. WebForm1 contain a server panel and server form.
3. In WebForm1.aspx.cs, I created a WebUserControl1 and attached it to panel
by:
WebUserControl1 oCtl = new WebUserControl1();
panel.Controls.Add(oCtl);
4. I have put a message in WebUserControl1::page_Load() to display the
validity (null or not null) of the server side table Table1
5. When I load the WebForm1, the Page_Load of WebUSerControl1 was loaded
twice (first problem), and both of them shows that the Table1 is null!
(problem 2)

Any one pls help...I am hopeless here. Thanks.

Calvin
 
K

Kevin Spencer

The correct syntax for adding a User Control programmatically to a Page or
Control would be to use the Page.LoadControl() method. Example:

WebUserControl1 oCtl = LoadControl("WebUserControl1.ascx");
panelID.Controls.Add(oCtl);

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
Big things are made up
of lots of little things.
 
C

Calvin Lai

Hi,
It there any difference in the process of creation between the two? (new Vs
LoadControl). Thanks for your help.
 
K

Kevin Spencer

It there any difference in the process of creation between the two? (new
Vs
LoadControl). Thanks for your help.

....besides the fact that one method works and the other doesn't? ;-)

I'm not sure offhand, although I'm sure if I spent some time researching it
I'm sure I could find out. I suspect it is because the User Control, like
the Page class, is a Templated Control. When you call New on the class, you
don't get the Template, just the CodeBehind class. Calling LoadControl()
instantiates the Template which inherits the CodeBehind.

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
Big things are made up
of lots of little things.
 

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