5
Answers

Error in Inserting image into Database in ASP.NET

Bineesh  VP

Bineesh VP

8y
279
1
Sir,
 
I am in a midst of an error while working on inserting image into database.
 
ASP.NET is the platform and SQL SERVER is the RDBMS.
 
My error is : -Failed to convert parameter value from a String to a Byte[].
 
 
Please go through the screenshot and  reply with the correct code.
 
 
 
 
Please take a look to the table structure where I want to insert my data:-
 
 
 
my sql server query to insert data:-
 
 
 And finally the c# code for insert function:-
 
 
Answers (5)
0
Vincent Maverick Durano

Vincent Maverick Durano

NA 19.1k 2.2m 8y
Your SQL parameter @asBookPhoto expects an Image datatype and you are passing a string to it that's why you are getting that error. You would need to convert the image to byte array and pass it to that parameter.
So change your code to this:
  1. cmd.Parameters.Add("@asBookPhoto",SqlDbType.Image).Value=imageByte;
Accepted
0
Bineesh  VP

Bineesh VP

NA 994 450k 8y
Finally I got the correct code:-
int length = flUpldCoverPhoto.PostedFile.ContentLength;
byte[] photo_aray = new byte[length];
HttpPostedFile postedFile = flUpldCoverPhoto.PostedFile;
postedFile.InputStream.Read(photo_aray, 0, length);
sqlCon.Open();
SqlCommand cmd = new SqlCommand("SaveBookDetails", sqlCon);
cmd.Parameters.Add("@asBookName", SqlDbType.VarChar).Value = txtBookName.Text;
cmd.Parameters.Add("@asBookPhoto", SqlDbType.Image).Value = photo_aray;
cmd.Parameters.Add("@asBookPrice", SqlDbType.Float).Value = txtBookPrice.Text.ToString();
cmd.Parameters.Add("@asAuthor", SqlDbType.VarChar).Value = txtBookAuthor.Text;
cmd.Parameters.Add("@asPublishedYear", SqlDbType.VarChar).Value = txtPublishYear.Text;
cmd.CommandType = CommandType.StoredProcedure;
int inCount = cmd.ExecuteNonQuery();
0
Bineesh  VP

Bineesh VP

NA 994 450k 8y
hi,
I am in the edge of getting the result in insert function, so I only need the solution for Failed to convert parameter value from a String to a Byte[].
the link you gave is totally different from my program flow.
0
Ravi Patel

Ravi Patel

NA 7.8k 532.4k 8y
Hi ,
check this
http://www.aspsnippets.com/Articles/How-to-save-insert-Image-in-Database-in-ASPNet-using-C-and-VBNet.aspx
0
Ranjit Powar

Ranjit Powar

NA 8.1k 496.5k 8y
Check this
http://www.c-sharpcorner.com/uploadfile/e628d9/inserting-retrieving-images-from-sql-server-database-without-using-stored-procedures/