<%@ Import Namespace="System.Collections" %>
<script language="vb" runat="server">
'Anytime you add a control dynamically, store enough information
'about that control to be able to recreate it. In this
'case since I'm always creating the same kind of textbox, I'm
'storing the id of each textbox in an ArrayList. Then I persist that
'ArrayList to ViewState. Anytime this page does a postback, I
'grab the ArrayList from ViewState, and for each id i find in the
'ArrayList, I'm going to create a control that has that same id.
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
'During postbacks, try to recreate any controls that were dynamically
'generated on this page.
If Page.IsPostBack Then
recreateControls()
End If
End Sub
Private Sub btnAddControl_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim list As ArrayList = getControlList()
Dim id As String = "Control" & list.Count.ToString()
addControl(createControl(id))
list.Add(id)
'Since we have modified the ArrayList, update viewstate.
ViewState.Item("ControlList") = list
End Sub
Private Function createControl(ByVal id As String) As Control
'This is just a helper method to create a new control.
Dim tb As TextBox = New TextBox()
tb.ID = id
Return tb
End Function
Private Sub addControl(ByVal c As Control)
'All this does is add a control to the panel followed by a linebreak.
pnlDynoControls.Controls.Add(c)
pnlDynoControls.Controls.Add(New LiteralControl("<br/>"))
End Sub
Private Sub recreateControls()
'Get a list control ids that have been dynamically created.
Dim list As ArrayList = getControlList()
'Create a control for each id and add it to the panel
For Each id As String in list
addControl(createControl(id))
Next
End Sub
Private Function getControlList() As ArrayList
'Try to get the ControlList from viewstate. The 'ControlList' is
'the ArrayList saved to viewstate that contains the id's of
'the controls that we ALWAYS need to recreate for every page.
Dim list As ArrayList
If Not ViewState.Item("ControlList") Is Nothing Then
list = CType(ViewState.Item("ControlList"), ArrayList)
Else
'No list yet, so create a new one.
list = new ArrayList()
End If
Return list
End Function
</script>
<html>
<head>
<title>Dyno Controls</title>
</head>
<body>
<form runat="server" ID="Form1">
<asp:Button Text="Add Control" ID="btnAddControl" Runat="server"
OnClick="btnAddControl_Click"/>
<asp:Panel ID="pnlDynoControls" Runat="server"/>
</form>
</body>
</html>