I am trying to create a page that has a variable number of FileUpload fields, depending on the number selected from a drop down list by the user.
my .apsx code is as follows;
<tr>
<td>Number of photo's to upload</td>
<td><asp:DropDownList ID="DLPhotoCount" runat="server" OnSelectedIndexChanged="OnSelectedIndexChanged_PhotoCount" AutoPostBack="true">
<asp:ListItem Text="..."></asp:ListItem>
<asp:ListItem Text="1"></asp:ListItem>
<asp:ListItem Text="2"></asp:ListItem>
</asp:DropDownList></td>
</tr>
<tr>
<td>Picture 1:</td>
<td><asp:FileUpload runat="server" ID="Pic1" Visible="false"/></td>
</tr>
<tr>
<td>Picture 2:</td>
<td><asp:FileUpload runat="server" ID="Pic2" Visible="false"/></td>
</tr>
<tr>
<td><asp:Button runat="server" ID="BtnUploadFiles" text="Upload Files" OnClick="OnClick_BtnUploadFiles" Visible="false"/></td>
</tr>
and my C# is;
protected void OnSelectedIndexChanged_PhotoCount(object sender, EventArgs e)
{
string Pic = "Pic";
int PicNo = Convert.ToInt32(DLPhotoCount.SelectedItem.Text);
if (DLPhotoCount.SelectedItem.Text != "...")
{
string StPicNo = Pic + PicNo;
do
{
FileUpload StPicNo.Visible = true;
PicNo = PicNo + 1;
}
while (PicNo < Convert.ToInt32(DLPhotoCount.SelectedItem.Text + 1));
BtnUploadFiles.Visible = true;
}
else
{
Pic1.Visible = false;
Pic2.Visible = false;
BtnUploadFiles.Visible = false;
}
}
Open to suggestions on any alternatives if this isn’t the best way to achieve the required functionality
Its a good practice to create file upload control dynamically based on the value selected from dropdownlist.
Sample examples to add fileupload controls using javascript are available under below links
http://www.aspsnippets.com/Articles/Uploading-Multiple-Files-using-JavaScript-Dynamic-FileUpload-Controls-in-ASP.Net.aspx
http://www.codeproject.com/Articles/24914/Multiple-Dynamic-File-Uploading
The advantage of this is you dont have to do a condition check in code behind file and no code change required if your business requires to add more file upload controls in future.