Dynamically Created User Controls not Initialising

J

John Sewell

Wonder if anyone can point me in the right direction!!

Basically I have built an ASP.net (VB.net) user control to display
data and this is comprised of a set of user controls that display
parts of the page (header, body etc.)

The problem I have is that this works fine when I just have the
control on a normal page, but does not work when I try to dynamically
add them to a page so that I can show a set of document on the same
page.

The page control (call it ctlPage) has 2 controls on it (ctlHeader,
ctlBody).
I did have to add each control to the area

'#Region " Web Form Designer Generated Code "'

in order to reference them in code (so I can call the init method with
the ID of them to show)

So ctlPage has a public method "ShowData" which simply calls the
methods on the controls on the page with the ID passed in.

The problem is that when control is created dynamically I get an error
that the controls on ctlPage are not set when I try and call ShowData.
I get the error:
"Object reference not set to an instance of an object", the objects
dont seem to be created.

The call to create ctlPage dynamically is:
theNewItem = New ctlPage
newCell.Controls.Add(theNewItem)
theNewItem.ShowData(dsData.Tables(0).Rows(lngLoop)("ItemID"))


Does anyone have an idea what I have done wrong or I am not
initialising the control(s) correctly?

Many thanks,

John
 
J

Jeffrey Palermo [MCP]

John,
When you dynamically load a user control, you must reference the .ascx
file that defines the user control. Also, you can put your code in the
Page_Load event handler.
theNewItem = Page.LoadControl("~/myvirtualpath/mycontrol.ascx") As
myControlType
newCell.Controls.Add(theNewItem)
theNewItem.ShowData(dsData.Tables(0).Rows(lngLoop)("ItemID"))

Do some reading on user controls and object-oriented development in general
because what you are doing is taking advantage of the object model of your
custom user control.

Best regards,
Jeffrey Palermo
 

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

Staff online

Members online

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top