动态创建的链接按钮上的Click事件不起作用

时间:2012-04-06 10:12:41

标签: c# asp.net

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

 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事件。我尝试了所有评论的选项,但它不起作用。代码有什么问题?

3 个答案:

答案 0 :(得分:3)

AddLinkBut​​tons()在何时何地调用?

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

根据您网页的逻辑,您的OnInit应该如下所示

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

    }

答案 1 :(得分:1)

代码似乎很好..

不明白AddLinkBut​​tons()方法中的lbTest是什么。

请从AddLinkBut​​tons()方法中删除此行。

lb = (LinkButton)lbTest;

希望这会奏效......

答案 2 :(得分:0)

在设置其属性后添加链接按钮。您的代码正在添加2磅按钮

        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

删除第一行