Search code examples
asp.netasp.net-4.0findcontrolasp.net-controls

Cannot FindControl within dynamically generated table


I have a dynamically generated table and for each row in the table there a some form textboxes for the user to complete and then submit the form. The problem i'm having is accessing the values within these fields once submitted.

The table has the Id=tableAssigneeChildren

This is the html produced by one of the textboxes i'm attempting to access:

<input name="ctl00$ContentPlaceHolder1$tChildName1" type="text" value="Test Name" id="tChildName1" />

The code below is what i am using just to test if I can access the above textbox:

Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click

    Dim childId As Integer

    For childId = 1 To CInt(iChild.Value)

        Response.Write(DirectCast(tableAssigneeChildren.FindControl("tChildName" & childId), TextBox).Text & "<br />")

    Next

End Sub

Thanks in advance for any help. J.


Solution

  • Dynamically created controls are lost on every postback. I would recommend adding the table to your markup because of following reasons:

    1. People often run into problems with there usercontrols not showing.

    2. Usercontrols events not getting fired, because the usercontrols do not exist in the markup instead are dynamically generated.

    3. There is no difference in the speed(page-size). You can toggle there visibility according to your needs.

    4. Much cleaner, elegant solution.

    Anyways if you really need adding table dynamically, have a look at this question Dynamic Controls and Postback and this tutorial https://web.archive.org/web/20210330142645/http://www.4guysfromrolla.com/articles/092904-1.aspx