我想提供上传多个文件然后下载的选项。我正在动态创建链接按钮,例如:

 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>"));

        }
    }


我的DownloadFile事件是:

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.");
    }
}


我在屏幕上看到链接按钮,但单击后再未调用DownloadFile事件。我尝试了所有已评论的选项,但无法正常工作。代码有什么问题?

最佳答案

在何处以及何时调用AddLinkBut​​tons()?

每次回发时,应在页面初始化期间调用它。

根据页面的逻辑,您的OnInit看起来应该像这样

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        AddLinkButtons();

    }

关于c# - 动态创建的链接按钮上的Click事件不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10042078/

10-10 17:03