how to store asp controls in an array?
I am using 10 asp:fileUpload control to upload multiple files
Now I want to check on each upload that it has file in it or not?
For that I took an array as
FileUpload uploadarr[] = new FileUpload[10];
but how do I check that it has posted file or not using 10 controls as FileUpload1,FileUpload2,FileUpload3...FileUpload10
HttpPostedFile myFile = FileUp开发者_JS百科load1.PostedFile;
Rather than storing each FileUpload in an array, you could make use of the HttpRequest.Files property to recurse all files posted to the page like so:
Markup
<div><asp:FileUpload ID="FileUpload1" runat="server" /></div>
<div><asp:FileUpload ID="FileUpload2" runat="server" /></div>
<div><asp:FileUpload ID="FileUpload3" runat="server" /></div>
<asp:Button ID="UploadFilesButton" runat="server" Text="Upload Files" OnClick="UploadFilesButton_Click" />
Code
protected void UploadFilesButton_Click(object sender, EventArgs e)
{
HttpFileCollection uploadedFiles = Request.Files;
for (int fileIndex = 0; fileIndex < uploadedFiles.Count; fileIndex++)
{
HttpPostedFile uploadedFile = uploadedFiles[fileIndex];
string fileName = System.IO.Path.GetFileName(uploadedFile.FileName);
if (!string.IsNullOrEmpty(fileName))
{
//Upload file as required
//uploadedFile.SaveAs("??");
}
}
}
Hope this helps.
With linq, try this:
var files = uploadarr.Where(x=>x.HasFile).Select(x=>x.PostedFile);
In page .cs file:
protected override void OnInit(EventArgs e)
{
for (int i = 0; i < 10; i++)
{
// Panel is ASP panel
Panel.Controls.Add(new FileUpload());
}
}
protected void Page_Load(object sender, EventArgs e)
{
foreach (var p in Panel.Controls)
{
if (p is FileUpload)
Response.Write(((FileUpload)p).FileName);
}
}
精彩评论