【发布时间】:2015-01-29 16:53:18
【问题描述】:
我想在 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);
}
}
当我单击链接按钮时将执行回发。 并且动态添加的链接按钮的所有属性都消失了。
如果我调试代码,该函数将永远不会被触发。 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();
}
谁能告诉我为什么点击动态构建链接按钮时没有触发该功能。
【问题讨论】:
-
始终在页面上添加控件,您将根据情况使刚才可见/不可见!
-
这是动态添加控件的诅咒,每次回发后它们都会被删除,因此您必须在每次回发事件后重新添加它们。
标签: c# asp.net entity-framework gridview linkbutton