2
Reply

Unable to cast object of type 'System.String' to type 'Syste

Paul Rajs

Paul Rajs

Feb 3 2016 1:38 AM
356


Hi, Developers ,

My code for load a attached file from database.

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
OleDbConnection con = Connection.DBconnection();
OleDbCommand com = new OleDbCommand("select Name,type,data from WordFiles where id=@id", con);
com.Parameters.AddWithValue("id", GridView1.SelectedRow.Cells[1].Text);
OleDbDataReader dr = com.ExecuteReader();
if (dr.Read())
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = dr["type"].ToString();
Response.AddHeader("content-disposition", "attachment;filename=" + dr["Name"].ToString()); // to open file prompt Box open or Save file
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite((byte[])dr["data"]);
Response.End();
}
}

if i click the download link na it will be downloaded.but
When i am try to download a attachment file it throws the following error.

Unable to cast object of type 'System.String' to type 'System.Byte[]'.
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.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Byte[]'.

Source Error:


Line 100: Response.Charset = "";
Line 101: Response.Cache.SetCacheability(HttpCacheability.NoCache);
Line 102: Response.BinaryWrite((byte[])dr["data"]);
Line 103: Response.End();
Line 104: }

So please help me to how i am resolve this error.

Thanks with
Paul.S

Answers (2)