Reputation: 1607
I want to give option to upload multiple files and then download it. I am creating link buttons Dynamically like:
private void AddLinkButtons()
{
string[] fileNames = (string[])Session["fileNames"];
string[] fileUrls = (string[])Session["fileUrls"];
if (fileNames != null)
{
for (int i = 0; i < fileUrls.Length - 1; i++)
{
LinkButton lb = new LinkButton();
phLinkButtons.Controls.Add(lb);
lb.Text = fileNames[i];
lb.CommandName = "url";
lb.CommandArgument = fileUrls[i];
lb.ID = "lbFile" + i;
//lb.Click +=this.DownloadFile;
lb.Attributes.Add("runat", "server");
lb.Click += new EventHandler(this.DownloadFile);
////lb.Command += new CommandEventHandler(DownloadFile);
phLinkButtons.Controls.Add(lb);
phLinkButtons.Controls.Add(new LiteralControl("<br>"));
}
}
And my DownloadFile event is:
protected void DownloadFile(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
string url = lb.CommandArgument;
System.IO.FileInfo file = new System.IO.FileInfo(url);
if (file.Exists)
{
try
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
}
catch (Exception ex)
{
}
}
else
{
Response.Write("This file does not exist.");
}
}
I am getting link buttons on screen but DownloadFile event is never called after clicking. i tried all options that are commented, but its not working. What is wrong in code?
Upvotes: 1
Views: 2725
Reputation: 48558
Add Link button after its properties have been set. Your Code is adding 2 lb buttons
phLinkButtons.Controls.Add(lb); //------1
lb.Text = fileNames[i];
lb.CommandName = "url";
lb.CommandArgument = fileUrls[i];
lb.ID = "lbFile" + i;
//lb.Click +=this.DownloadFile;
lb.Attributes.Add("runat", "server");
lb.Click += new EventHandler(this.DownloadFile);
////lb.Command += new CommandEventHandler(DownloadFile);
phLinkButtons.Controls.Add(lb); //-------------------2
Remove First line
Upvotes: 0
Reputation: 547
code seems fine ..
dont understand what is lbTest in AddLinkButtons() method.
please remove this line from AddLinkButtons() method.
lb = (LinkButton)lbTest;
Hope that will works...
Upvotes: 1
Reputation: 15413
Where and when is AddLinkButtons() called ?
It should be called during init of your page, on each postback.
Depending on the logic of your page, your OnInit should look like this
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
AddLinkButtons();
}
Upvotes: 3