Cannot access dynamically created user controls

K

Kees de Winter

Hi,

I dynamically create several user controls of the same type but then on
postback I can not access the properties of the user controls. Why is that??
I get the "Object reference not set to an instance of an object. ".

Here is how I create the user controls:
For intRoom As Integer = 0 To totalRooms - 1
Dim myUC As Control = Page.LoadControl("Entry_Guestnames.ascx")
CType(myUC, Entry_Guestnames).roomNo = intRoom
CType(myUC, Entry_Guestnames).totalAdults = intAdultsInRoom
myUC.ID = "UC_ID_" + intRoom.ToString
PlaceHolder1.Controls.Add(myUC)
Next

On postback I try to access a property Firstname.
Dim uc As New Entry_Guestnames
uc = CType(FindControl("UC_ID_0"), Entry_Guestnames)
Response.Write(uc.FirstName)

The last line gives me the error. What am I doing wrong?

Thanks,
Kees de Winter
 
M

Mark Rae

I dynamically create several user controls

Did you create them in the Page_Init method...? If not, that's where you
need to create them. If you create them in Page_Load, chances are it won't
work properly...
On postback I try to access a property Firstname.
The last line gives me the error. What am I doing wrong?

Dynamic controls do not survive a postback - they need to be created each
time the page loads.
 
K

Kees de Winter

Thanks for your suggestions Mark. But I got it to work after I found out
that I needed to change
Dim uc As New Entry_Guestnames
uc = CType(FindControl("UC_ID_0"), Entry_Guestnames)

to:

Dim uc As Entry_Guestnames
uc = CType(PlaceHolder1.FindControl("UC_ID_0"), Entry_Guestnames)

The controls were added to PlaceHolder1 so I needed to use FindControl from
that control.
--
Kees

Mark Rae said:
Did you create them in the Page_Init method...? If not, that's where you
need to create them. If you create them in Page_Load, chances are it won't
work properly...

The user controls seem to be created allright, when I look at the HTML. I
tried moving the creation to OnInit but nothing 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,967
Messages
2,570,148
Members
46,694
Latest member
LetaCadwal

Latest Threads

Top