Another dynamic usercontrol issue

  • Thread starter Thread starter Bryan
  • Start date Start date
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
 
Hello Bryan,

You need to do

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

phControl.Controls.Add(ctl)

Page.LoadControl returns a Control. This is what you need to add to your
controls collection.
 
That did the trick!!!

Thanks

Matt Berther said:
Hello Bryan,

You need to do

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

phControl.Controls.Add(ctl)

Page.LoadControl returns a Control. This is what you need to add to your
controls collection.
 
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.
 
Back
Top