問題
使用 GridView.TemplateField實作Link Button觸發下載檔案的動作
解決方法
在LinkButton事件哩,加入程式碼: .cs
protected void lbtFileName_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)sender;
TableCell tc = (TableCell)btn.Parent;
GridViewRow gvr = (GridViewRow)tc.Parent;
int rowindex = gvr.RowIndex;
//資料來源
DataTable tb = db.GetContentByGID(Convert.ToInt32(gvNotice.DataKeys[rowindex].Value));
DataRow row = tb [0]; //下載檔案
Response.Clear();
string fileName = Server.UrlPathEncode(Convert.ToString(row["FileName"]));
Response.Expires = 0;
Response.Buffer = true;
Response.AddHeader("Accept-Language", "zh-tw");
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", fileName)); //Response.Cache.SetNoStore();
//Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Length", row.NContent.Length.ToString());
Response.BinaryWrite(row.NContent);
Response.End();
}
.aspx設定LinkButton顯示的文字:
<asp:TemplateField HeaderText="文件名稱" SortExpression="FileName"> <ItemTemplate> <asp:LinkButton ID="lbtFileName" runat="server" CommandName="OpenFile" onclick="lbtFileName_Click" > <%#Eval("FileName") %></asp:LinkButton> </ItemTemplate> </asp:TemplateField>
沒有留言:
張貼留言