在下面的代码中,我在会话中得到附件文件名,我已经绑定了documnetid,attachmentname和download.but当我选择第一个attachmnet文件名时,它正在下载第二个attchmt文件名。我的目标是下载我在网格视图中选择的内容。 例如
document id attchfilename download
1 xxx view
2 yyy view
标记
<asp:GridView ID="Attchdwnld" runat="server"
AllowPaging="true"
AllowSorting="true"
AlternatingRowStyle-CssClass="alt"
AutoGenerateColumns="false"
CellPadding="4"
CssClass="mGrid"
ForeColor="#333333"
PageSize="10"
PageSize-Mode="NumericPages"
PagerStyle-CssClass="pgr"
PagerStyle-Visible="true"
ShowFooter="false"
Width="100%"
OnRowCommand="Attchdwnld_RowCommand" >
<Columns>
<asp:TemplateField HeaderText="DocumentID" ItemStyle-Width="200px">
<ItemTemplate>
<asp:Label ID="DocumentID" runat="server" Text='<%#Eval("DocumentID") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="AttachmentFileName" ItemStyle-Width="200px">
<ItemTemplate>
<asp:Label ID="AttachmentFileName" runat="server" Text='<%#Eval("AttachmentFileName") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DownLoad" ItemStyle-Width="150px">
<ItemTemplate>
<asp:LinkButton ID="lnlbtnAttch" runat="server" Text="View" CommandName="Edit">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle Font-Bold="True" ForeColor="White" />
</asp:GridView>
代码隐藏
protected void Attchdwnld_RowCommand(object sender, GridViewCommandEventArgs e)
{
var SearchDoc = (SearchDoc)Session["Documentname"];
lblMessage.Text = SearchDoc.AttachmentFileName;
string fileurl = "C:\\Search\\" + stName + "\\" + strtFolder + "\\" + lblMessage.Text;
string filename = fileurl;
if (filename != "")
{
string path = filename;
System.IO.FileInfo file = new System.IO.FileInfo(path);
if (file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
}
else
{
Response.Write("This file does not exist.");
}
}
}
答案 0 :(得分:0)
我不明白为什么你应该在代码中存储Session["Documentname"]
。所以我省略了那一部分。
试试此代码
protected void Attchdwnld_RowCommand(object sender, GridViewCommandEventArgs e)
{
// gets the clicked row of your GridView
var row = ((LinkButton)e.CommandSource).NamingContainer as GridViewRow;
//gets the filename in the cliked row
var attachmentNameLabel = row.FindControl("AttachmentFileName") as Label;
//store it to lblMessage's Text
lblMessage.Text = attachmentNameLabel.Text;
var filePath = String.Format("C:\\Search\\{0}\\{1}\\{2}",
stName, strtFolder, lblMessage.Text);
var file = new System.IO.FileInfo(filePath);
if (file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
}
else
{
Response.Write("This file does not exist.");
}
}