I have added a download link in my gridview. When i click on that file does not download but I can see the response in chrome.Click to see response in chrome I can see the file data in chrome developer tool response tab but the download code does not work. Please help.
protected void GridView1_RowCommand1(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "downloadfile")
{
int rowId = Convert.ToInt32(e.CommandArgument);
int fileId = Convert.ToInt32(((Label)GridView1.Rows[rowId].FindControl("lblfileid")).Text);
string fileName;
string constr = ConfigurationManager.ConnectionStrings["DMS"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select FileName,FileData,FileContentType from Attachment where FileId=@fileId";
cmd.Parameters.AddWithValue("@fileId", fileId);
cmd.Connection = con;
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.Read())
{
fileName = sdr["FileName"].ToString();
Response.ContentType = sdr["FileContentType"].ToString();
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + sdr["FileName"] + "\"");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite((byte[])sdr["FileData"]);
Response.Flush(); // Sends all currently buffered output to the client.
Response.SuppressContent = true; // Gets or sets a value indicating whether to send HTTP content to the client.
HttpContext.Current.ApplicationInstance.CompleteRequest();
//Response.TransmitFile(@"c:\ip.txt");
}
con.Close();
}
}
}
catch (Exception ex)
{
}
Response.End();
}
<asp:GridView ID="GridView1" runat="server" DataKeyNames="FileId" OnRowDeleting="GridView1_RowDeleting" OnRowDataBound="GridView1_RowDataBound" Width="426px" Height="169px" OnRowCommand="GridView1_RowCommand1" AutoGenerateColumns="false">
<Columns>
<asp:HyperLinkField DataTextField="FileName" InsertVisible="False" HeaderText="File Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" Text="Download" CommandArgument='<%# Eval("fileID") %>' runat="server" CommandName="downloadfile" OnClick="lnkDownload_Click" CausesValidation="false"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnlDwn" Text="Download file" runat="server" OnClick="lnlDwn_Click" CommandArgument='<%# Eval("fileID") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblfileid" Text='<%# Bind("FileId") %>' runat="server" Visible="false"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField CommandName="downloadfile" HeaderText="action" Text="Download" />
<asp:ButtonField CommandName="DeleteFile" HeaderText="action" Text="Delete File" />
</Columns>
</asp:GridView>