fokz8 fokz8 - 4 days ago 5
ASP.NET (C#) Question

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

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

My database table:

Order

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";
break;
case ".png":
contentType = "image/png";
break;
case ".gif":
contentType = "image/gif";
break;
case ".pdf":
contentType = "application/pdf";
break;
}
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;
conn.Open();
cmd.ExecuteNonQuery();
Response.Write("Success!");
}
}
}
}


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

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)"
Comments