Cannot access dynamically created user controls

Discussion in 'ASP .Net' started by Kees de Winter, Jan 29, 2007.

  1. 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
     
    Kees de Winter, Jan 29, 2007
    #1
    1. Advertisements

  2. Kees de Winter

    Mark Rae Guest

    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...
    Dynamic controls do not survive a postback - they need to be created each
    time the page loads.
     
    Mark Rae, Jan 29, 2007
    #2
    1. Advertisements

  3. 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

    The user controls seem to be created allright, when I look at the HTML. I
    tried moving the creation to OnInit but nothing changed.
     
    Kees de Winter, Jan 29, 2007
    #3
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.