2014-12-01 42 views
1

我想在GridView中动态创建链接按钮,并在Command事件中我想下载存储在数据库中的文件作为varbinary。动态构建链接按钮,不起作用

如果有在的RowDataBound方法以下代码:

var attachments = (from a in dbContext.Attachments.Where(i => (i.ID == id)) select a); 
       if (attachments.Any()) 
       {      
        foreach (Attachments Att in attachments) 
        { 
         LinkButton lb = new LinkButton(); 
         lb.CssClass = "download"; 
         lb.Text = Att.FileName; 
         lb.CommandName = "Attachment"; 
         lb.CommandArgument = Att.AttachmentID.ToString(); 
         lb.Command += ShowAttachmentFile; 
         e.Row.Cells[4].Controls.Add(lb); 
        } 
       } 

当我在一个LinkBut​​ton单击回发将被执行。 动态添加的链接按钮的每个属性都消失了。

如果我调试代码,该函数将永远不会被触发。 的commant事件方法的代码如下所示:

protected void ShowAttachmentFile(object sender, CommandEventArgs e) 
     { 
      int fileID = Int32.Parse(e.CommandArgument.ToString()); 
      var downloadResult = (from a in dbContext.Attachments.Where(i => (i.id== fileID)) select a).First(); 

      Byte[] bytes = (Byte[])downloadResult.Data; 
      Response.Buffer = true; 
      Response.Charset = ""; 
      Response.Cache.SetCacheability(HttpCacheability.NoCache); 
      Response.ContentType = downloadResult.ContentType; 
      Response.AddHeader("content-disposition", "attachment;filename=" 
      + downloadResult.FileName); 
      Response.BinaryWrite(bytes); 
      Response.Flush(); 
      Response.End(); 
     } 

谁能告诉我,为什么在一个动态生成LinkBut​​ton的点击时不会触发功能。

+0

总是在页面上添加控件,您将根据情况使可见/不可见! – mybirthname 2014-12-01 16:27:45

+0

这是动态添加控件的诅咒,在每次回发之后,它们都会被删除,因此您必须在每次回发事件后重新添加它们。 – KhanZeeshan 2014-12-01 17:27:59

回答

1

问题是你需要在Postback上重新绑定GirdView。否则,在回发时,那些动态填充的按钮将变为null,并且它们不能触发ShowAttachmentFile事件。

最简单的方法是在设计时在GridView中添加下载按钮。然后在运行时显示/隐藏rowdatabound - foreach循环

+0

感谢您的更新。我将这些动态添加,因为它取决于查询结果必须添加多少buttonlinks。 – 2014-12-02 07:19:29

+0

在单行中可以有多个下载链接 – 2014-12-02 07:45:26

0

谢谢你的所有意见。 我通过删除isPostback检查解决了我的问题。

+0

如果问题得到解决,则将任何一个建议标记为已回答。 – 2014-12-02 08:19:34