Another dynamic usercontrol issue

B

Bryan

Hello All,

I have a page that dynamically adds one of many usercontrols to a
placeholder on the main page based on a parameter passed to the page.

Here is my problem.

The usercontrol may have something as simple as a label or a datagrid and I
get the same error.

The control renders in the designer and the code has the object declared.
Basically everything is were it should be. Once you run the page and try to
assign text to a label or bind data to a data grid you get a "Object
reference not set to an instance of an object." error. What the heck is
going on? This control works in a page that doesn't load it dynamic.

Does anyone have any ideas?

-----------------------------
MyControl.ascx - Code
<%@ Control Language="vb" AutoEventWireup="false"
Codebehind="floorplans.ascx.vb" Inherits="Tandem.floorplans"
TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %>
<div id="text">
<asp:Label id="Label1" runat="server"></asp:Label>
</div>

-----------------------------
MyControl.ascx.vb - Code

Protected WithEvents Label1 As System.Web.UI.WebControls.Label

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
If Not Page.IsPostBack Then
LoadContent()
End If
End Sub

Private Sub LoadContent()
Label1.Text = "Some Text"
End Sub

-----------------------------
This is the code that adds the control on the page side. The function that
calls the following code is in the onload event of the page

Dim ctl As New MyConrol

ctl.PropertyID = PropertyID
Page.LoadControl("controls/MyControl.ascx")
phControl.Controls.Add(ctl)


Thanks,
B
 
P

Paul Hatcher

Bryan

Try moving the code to the CreateChildControls method of the page which is
overridable

Paul
 
B

Bryan

Here is the resolution for all who would like to know.

Old code:
Dim ctl As New MyConrol
ctl.PropertyID = PropertyID
Page.LoadControl("controls/MyControl.ascx")
phControl.Controls.Add(ctl)


New Code:
Dim ctl As MyConrol
ctl = Page.LoadControl("controls/MyControl.ascx")
ctl.PropertyID = PropertyID
phControl.Controls.Add(ctl)

That was all that needed to be changed.
 

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,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top