First, let me start off by saying I am using ASP.NET 2.0 with VB as the default language using Visual Studio 2005.
I have a form that has an asp:panel on it that is seeded with an iniitial control. Through the use of the form, additional controls may be dynamically added to the form. The problem is that none of the dynamically added controls persist on a postback. Here's some example code the exhibits the behavior I am seeing.
First, the HTML:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="test2.aspx.vb" Inherits="test2" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <asp:Panel ID="divNav" runat="server" EnableViewState="true" Visible="true"> <asp:LinkButton ID="lbHome" runat="server">0</asp:LinkButton> </asp:Panel> <asp:Button ID="Button1" runat="server" Text="Add Another Line" /> </form> </body> </html>
And now, the code behind:
Partial Class test2 Inherits System.Web.UI.Page Private intLineNum As Integer Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then intLineNum = 1 Else intLineNum += 1 End If End Sub Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click Dim lb As New LinkButton lb.ID = "lb" & intLineNum lb.Text = intLineNum Me.divNav.Controls.AddAt(Me.divNav.Controls.Count, New LiteralControl("<br />")) Me.divNav.Controls.AddAt(Me.divNav.Controls.Count, (lb)) End Sub End Class
What happens is that when you click the button to add another LinkButton, it does indeed add a new LinkButton. The problem is that it won't add any others beyond that. I've tried both the Load and Pre_Init events for the page, but my code does not work in either of them.
I've also tried getting a count of the controls on the panel and using the AddAt method to add the new controls at the end of the array, but again I cannot find a way to make that work as it only ever sees at most two controls.
Can someone help out with this? Thanks.