Hello,
For Download a file I like to use the below code that I found in the net. So I have made a grid view that first column is file name.
Now when I run the application, I have the message "
This file does not exist.".
So for checking my code I have added statement
Response.Write(filename)<code> after statement <code>string filename = rowItem.Cells[0].ToString()
, so after running the application it returns
System.Web.UI.WebControls.DataControlFieldCell
for the value " filename".
Please help what is the problem.
------------------------------------------------------
protected void lnkPath_OnClick(object sender, EventArgs e)
{
GridViewRow datarow = (GridViewRow)(((Control)sender).NamingContainer);
int i = datarow.RowIndex;
foreach (GridViewRow rowItem in grdv.Rows)
{
if (rowItem.RowIndex == i)
{
string filename = rowItem.Cells[0].ToString();
if (filename != "")
{
string path = Server.MapPath(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.");
}
}
}
}
}
----------------------------------------------
<asp:GridView ID="grdv" runat="server" DataSourceID="SqlDataSource1" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Title" >
<ItemTemplate>
<asp:LinkButton ID="lnkPath" runat="server" Text= '<%# Bind("Coach_First") %>' OnClick="lnkPath_OnClick" ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DocsID" >
<ItemTemplate>
<asp:Label ID="lblDocsID" runat="server" Text='<%# Bind("CoachId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProjectID" >
<ItemTemplate>
<asp:Label ID="lblProjectID" runat="server" Text='<%# Bind("Coach_Last") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Webpath" >
<ItemTemplate>
<asp:Label ID="lblWebpath" runat="server" Text='<%# Bind("Coach_Email") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ConnectionString="<%$ ConnectionStrings:conn %>" ID="SqlDataSource1"
runat="server" SelectCommand="SELECT top 5 CoachId, Coach_First, Coach_Last, Coach_Email from tblCoach">
</asp:SqlDataSource>