fokz8 fokz8 - 10 months ago 90
ASP.NET (C#) Question

Failed to convert parameter value from a Byte[] to a String

I'm building an app with c# I need to insert some data into database. Everything works fine, but i get problem with inserting an image.

My database table:


OrderID int
description varchar(50)
numOfItems int
material varchar(50)
image varbinary(max)

My code for inserting data into database

protected void btnAddItem_Click(object sender, EventArgs e)
string filepath = fileUpload.PostedFile.FileName;
string filename = Path.GetFileName(filepath);
string ext = Path.GetExtension(filename);
string contentType = String.Empty;

switch (ext)
case ".jpg":
contentType = "image/jpg";
case ".png":
contentType = "image/png";
case ".gif":
contentType = "image/gif";
case ".pdf":
contentType = "application/pdf";
if (contentType != String.Empty)
Stream fs = fileUpload.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);

string kon = ConfigurationManager.ConnectionStrings["mk"].ConnectionString;

using (SqlConnection conn = new SqlConnection(kon))
using (SqlCommand cmd = new SqlCommand("INSERT INTO Order(description, numOfItems, material, image"))
cmd.Connection = conn;
cmd.Parameters.AddWithValue("@description", inputTextArea.Text);
cmd.Parameters.AddWithValue("@numOfItems", inputTextArea.Text);
cmd.Parameters.AddWithValue("@material", inputTextArea.Text);
cmd.Parameters.Add("@image", SqlDbType.VarChar).Value = bytes;

When i do that, i get the following error : Failed to convert parameter value from a Byte[] to a String.

Any ideas?

UPDATE - new error

Incorrect syntax near 'image '. error. any ideas?

Answer Source

For the parameter @image the passed value is a byte array but you ware specified that the input will be VarChar change it to Binary. so the statement that add specific parameter will be looks like the following

cmd.Parameters.Add("@image", SqlDbType.Binary).Value = bytes;

And you have to add the placeholders to your query, which means the query text should be like this:

"INSERT INTO Order(description, numOfItems, material, image)values(@description, @numOfItems,@material,@image)"