我想在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