hello ,
I am trying add link button like this to download file from sql data user, pdf, image , etc..
backupmyfile : varbinary(MAX)
<asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="DownloadFile"
CommandArgument='<%# Eval("Id") %>'></asp:LinkButton>
when i try search user data then pres the download i am not get the file download
protected void DownloadFile(object sender, EventArgs e)
{
string str = ConfigurationManager.ConnectionStrings["kankonConnectionString"].ConnectionString;
int id = int.Parse((sender as LinkButton).CommandArgument);
byte[] bytes;
string fileName, contentType;
using (SqlConnection con = new SqlConnection(str))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select name, civilid, Namefile, backupmyfile, ContentType from Table_infoname where Id=@Id";
cmd.Parameters.AddWithValue("@Id", id);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["backupmyfile"];
contentType = sdr["ContentType"].ToString();
fileName = sdr["Namefile"].ToString();
}
con.Close();
}
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
I am get this error
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Invalid attempt to read when no data exists.
Source Error:
Line 647: {
Line 648: sdr.Read();
Line 649: bytes = (byte[])sdr["backupmyfile"];
Line 650: contentType = sdr["ContentType"].ToString();
Line 651: fileName = sdr["Namefile"].ToString();
|