WenHao
WenHao

Reputation: 1235

Fail to continously add new control into Panel/Placeholder during partial postback

I want to create a dynamic form where user has a button to click on it. When the button clicked, it will trigger a partial postback and add a new control into a placeholder.

My problem is, when the button is clicked for the first time, it able to create a new control in the placeholder. But it will not create more than that even though i have clicked the button for few times.

<asp:ScriptManager ID="ScriptManager1" EnablePartialRendering="true" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Button ID="Button1" runat="server" Text="Add images" OnClick="Button1_Click" />
                <asp:HiddenField ID="HiddenField1" runat="server" Value="1" />
                <br />
                <asp:Panel ID="PlaceHolder1" runat="server">
                    <asp:FileUpload ID="FileUpload1" runat="server" />
                </asp:Panel>
            </ContentTemplate>
        </asp:UpdatePanel>

Code behind:

protected void Button1_Click(object sender, EventArgs e)
    {

        PlaceHolder1.Controls.Add(new FileUpload());

    }

Upvotes: 0

Views: 332

Answers (1)

rdans
rdans

Reputation: 2157

Unless a dynamically added control is added at the preinit or init stage, it does not persist beyond a post back. So when the button is clicked for the second time, the first added control is lost and then the button logic adds a control again, leaving you with one control every time. For a control added after the init stage, you would need to store its state and recreate it on each postback. This is described int this article:

http://www.codeproject.com/Articles/3684/Retaining-State-for-Dynamically-Created-Controls-i

You may also be able to achieve your goals without using dynamically added controls. One possible approach is to use a ListView control, add a FileUpload control to its ItemTemplate and add a new record to the list view data source every time the button is clicked.

Upvotes: 1

Related Questions