• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1124
  • Last Modified:

If I dynamically add controls in ASP.NET, how do I retrieve their values on subsequent posting?

If I dynamically add controls in ASP.NET, how do I retrieve their values on subsequent posting?
For example this form:

<form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
            <asp:ListItem>1</asp:ListItem>
            <asp:ListItem>2</asp:ListItem>
            <asp:ListItem>3</asp:ListItem>
        </asp:DropDownList><br />
        <asp:Panel ID="Panel1" runat="server" Height="50px" Width="436px">
            <asp:FileUpload ID="fileUpload1" runat="server" Width="429px" /></asp:Panel>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
        <br />
        <br />
        <asp:ListBox ID="ListBox1" runat="server" Width="379px"></asp:ListBox></div>
    </form>

has a dropdown list that when changed runs this:

        for (int i = 2; i < Convert.ToInt32(DropDownList1.SelectedIndex)+ 2; i++)
        {
            FileUpload fileUpload = new FileUpload();
            fileUpload.ID = "fileUpload" + i.ToString();
            Panel1.Controls.Add(fileUpload);
        }

I need code for the button that will get the file names from however many controls were added with the drop down list.
0
ksaul
Asked:
ksaul
  • 2
  • 2
3 Solutions
 
Bob LearnedCommented:
If you dynamically add controls, then you need to recreate them in the Page_Init event handler.

Bob
0
 
ksaulAuthor Commented:
Bob,
Can you give me some sample code of how to do that?  I would need to retain entered values when I re-create them.
0
 
Bob LearnedCommented:
If the page has the ViewState enabled, and the control has a ViewState, then when you recreate the control in the Page_Init, the entered values will be retained.  The problem that you are going to have is that the FileUpload control will not retain it's previous value, nor can you specify one.

Bob
0
 
ksaulAuthor Commented:
I'm going to split points for your suggestions.

I decided that for this situation it was better to create 25 design-time FileUpload controls setting their style property to display:none and then use javascript to show and enable as many as the user needed.  That made looping through the controls after the post much easier.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now