我想在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);
}
}
當我在一個LinkButton單擊回發將被執行。 動態添加的鏈接按鈕的每個屬性都消失了。
如果我調試代碼,該函數將永遠不會被觸發。 的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();
}
誰能告訴我,爲什麼在一個動態生成LinkButton的點擊時不會觸發功能。
總是在頁面上添加控件,您將根據情況使可見/不可見! – mybirthname 2014-12-01 16:27:45
這是動態添加控件的詛咒,在每次回發之後,它們都會被刪除,因此您必須在每次回發事件後重新添加它們。 – KhanZeeshan 2014-12-01 17:27:59