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!
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'sinit
event.Recommandable readings:
Or you use one of the builtin Data-Bound Control like Repeater that do this automatically. You only have to set their
DataSource
and callDataBind
().Here are answers of me on similar questions with implementations: