简体   繁体   中英

dynamically adding controls does not displayed inside panel in asp.net web form

I have a web form with a table where one row contains panel to add fileupload controls dynamically

the code is as below

      <tr> 
     <td  style="width:70%;display:block; overflow:visible;" >
        <asp:Panel ID="ImagePanel" runat="server">
        <uc1:AddNewImage runat="server" id="AddNewImage" /></asp:Panel>
        <asp:Button ID="AddImage"  OnClick="Unnamed_Click" Text="Add New Image" runat="server" CausesValidation="False" />
        <asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server" ErrorMessage="Please Enter Model Items" ForeColor="Red" ControlToValidate="TxtItems"></asp:RequiredFieldValidator>
    </td>
    </tr>

In button click event i am adding new usercontrol to ImagePanel using following code

        Controls.AddNewImage Obj = (Controls.AddNewImage)LoadControl(@"~/Controls/AddNewImage.ascx");
        this.ImagePanel.Controls.Add(Obj);

Problem is only two controls are displayed inside the panel, i need to allow upto five controls, but these controls are not displayed inside panel. What should i need to do to get displayed these controls inside the panel. do i need to set any css for Panel. Panel is inside a tag.

That's because dynamically added controls are cleared when page PostBack. Simply solution is to add <asp:HiddenField id="hidCount" runat="server" value="1"/> and update your click event like this:

int count = int.Parse(hidCount.Value)++;
hidCount.Value = count.ToString();
for(i=0;i< count;i++) {
        Controls.AddNewImage Obj = (Controls.AddNewImage)LoadControl(@"~/Controls/AddNewImage.ascx");
        this.ImagePanel.Controls.Add(Obj);
}

This will work perfectly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM