Take the 2-minute tour ×

I'm trying to build a form which generates itself as it is used. I have created a really simplistic example, loosely related to what I'm trying to do below, but which demonstrates the problem.

The user types a word in the text box, clicks the Button and a new TextBox is loaded into a Panel, with the value in the original TextBox that the user has entered. The user should then be able to type something else/the same and create another text box with that in it by clicking the button, basically permitting 0,1,..,n textboxes appearing above the "txtFeeder" TextBox on the form.

The problem is that everytime you click the button, it doesn't add a new control, it seems to just update the one that has already been created with the new (incremental) ID. I'm not sure if I'm doing something wrong, or if what I'm trying to do can't be done (which I find hard to believe)?

Here's the .aspx...

<form id="frmMain" runat="server">
    <asp:Panel ID="pnlAdded" runat="server"></asp:Panel>
    <asp:TextBox ID="txtFeeder" runat="server"></asp:TextBox>
    <asp:Button ID="btnFeedPanel" runat="server" Text="Button" />

...and here's the .aspx.vb...

    If Not IsPostBack Then
        ViewState.Add("elementCount", 0)
    End If
End Sub
Protected Sub btnFeedPanel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFeedPanel.Click
    ViewState("elementCount") += 1
    Dim txtNew = New TextBox
    txtNew.ID = "txtElement" & ViewState("elementCount")
    txtNew.Text = txtFeeder.Text
    txtNew = Nothing
End Sub


share|improve this question

2 Answers 2

up vote 2 down vote accepted

On PostBack you need to explicitly regenerate the buttons from ViewState (you check the added counter you have in the viewstate and regenerate the added buttons) - otherwise they'll be gone (and only the original one will appear, as you're experiencing).

Have a look at this question, the guy is trying to achieve smt extremely similar to what you're looking for (maintaining a bunch of dynamic buttons and regenerating them on postback).

share|improve this answer
Thanks - the link is a great help too. –  Chris Nov 20 '09 at 19:19

Controls that are added to a page dynamically are not automatically retained between form posts. The control itself isn't preserved in the page's view state. I think you'll need to rebuild all of the previously added fields every time a postback occurs.

share|improve this answer

Your Answer


