views:

218

answers:

2

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" />
</form>

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

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    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
    pnlAdded.Controls.Add(txtNew)
    txtNew = Nothing
End Sub

Thanks

+2  A: 

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.

alex
+1  A: 

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).

JohnIdol
Thanks - the link is a great help too.
Chris