views:

372

answers:

2

My problem is each time I hit the "Test" button, only one textbox is created. If I click two times, I would like two textbox to appear.

I try this solution, and it's seems to work fine except for only one thing. Each text the textbox are (re)created so I loose the value the user have entered...

Aspx:

<asp:UpdatePanel ID="upTest" runat="server">
    <ContentTemplate>
        <asp:Button ID="btnTest" runat="server" Text="Test" OnClick="btnTest_Click" />
        <asp:Panel ID="pnTest" runat="server" />
    </ContentTemplate>
</asp:UpdatePanel>

Code-behind

protected void btnTest_Click(object sender, EventArgs e)
{
    pnTest.Controls.Add(new TextBox());
}
+1  A: 

The problem is that you are expecting the UpdatePanel to handle your viewstate and it only really works for pre-defined controls. Because your making them on the fly there is no viewstate for them so you will need to do all the viewstate management yourself.

You could store the values on each postback and then re-insert them once the controls are recreated but there is no built in functionality to do this. Each time you postback you could store the the control name as the viewstate key and then store the value. Then when you recreate the control you can just match up the control names (which should be the same) and values with the newly created controls except for obviously the newest one which wouldn't have an entry stored yet.

Kelsey
Could you provide me an example or a link to what your explaining because I try but I achieve no success...
Melursus
A: 

This link should point you in the right direction:

Dynamic Web Controls, Postbacks, and View State

rick schott