2014-12-01 68 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