Loop through Dynamically Created Controls

2019-09-14 23:08发布

问题:

What I am trying to do is dynamically create a bunch of dropdown lists and then I want to loop through them and update the database with those values, but the problem I am facing is that I create the dropdown lists, but then when I go back to loop through them they are no longer in the panel. I don't know why but when I am debugging I have a count of 50 controls in pnlTeacherSelect right up until I press the button that calls prcChoose.

Called on Page Load

Sub prcSetTeachers()
    For Each Subject In ds.Tables("Subject").Rows
        Dim Temp As New DropDownList
        pnlTeacherSelect.Controls.Add(Temp)
        Temp.ID = "drp" & Subject.Item(0) & "s" & Child.Item(0)
    Next
End Sub

Called on Clicking a button

Sub prcChoose()
    For Each DropDownList In pnlTeacherSelect.Controls.OfType(Of DropDownList)

    'This is never executed

    Next
End Sub

Any ideas what's causing it? Thanks in advance!

回答1:

You have to recreate all dynamically created controls on every postback(in load event at the latest). You also have to ensure that they get the same ID as before to trigger events and maintain ViewState.

If you know the number of controls to create(which could be stored in ViewState) you can derive the ID from the counter variable by appending it to the control-id. Then you can recreate them with the correct ID in page's init event.

Recommandable readings:

  • TRULY Understanding Dynamic Controls
  • Page-Lifecycle

Or you use one of the builtin Data-Bound Control like Repeater that do this automatically. You only have to set their DataSource and call DataBind().

Here are answers of me on similar questions with implementations:

  • C#
  • VB.NET (+ C#)