Click here to Skip to main content
16,021,041 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello

I have an image datatype in sql table. and i am adding values through folowing lines.

cmd.Parameters.Add("@Image", SqlDbType.Image).Value = convert.tobyte(txtImage.Text.Trim())


Now because of the image i am getting convert function error

Invalid cast from 'System.String' to 'System.Byte[]'.

Please help

I have a upload function for the image. which is correct.

Please can anyone help me with this.
can anyone give me the correct code for the above line.
Posted
Updated 18-Jun-12 18:33pm
v2

Hi friend,

Check the fallowing code, this is working for me....

C#
if (fileupload1.HasFile)
{
   byte [] productImage = fileupload1.FileBytes;

   con.Open();
    SqlCommand cmd = new SqlCommand("SP_SetUserDetails", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@Username", txtuname.Text);
    cmd.Parameters.AddWithValue("@EmailID", txtEmail.Text);
    cmd.Parameters.AddWithValue("@Password", txtpass.Text);
    cmd.Parameters.AddWithValue("@Image", productImage);
    cmd.Parameters.AddWithValue("@Hobbies", str);
    cmd.Parameters.AddWithValue("@country", txtcountry.Text);
    cmd.Parameters.AddWithValue("@Status", sts.ToString());
    //cmd.ExecuteNonQuery();
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    Gridview1.DataSource = ds;
    //Gridview1.DataBind();
    BindGrid();
    //con.Close();

}
 
Share this answer
 
v2
Try below code:

C#
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
 MemoryStream ms = new MemoryStream();
 imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
 return  ms.ToArray();
}


Now save the byte array in the database.

Call the above method while saving image in the database:

C#
command.Parameters.Add("@IMAGE", SqlDbType.VarBinary).Value = ConvertImageToByteArray(PictureBox1.Image);




While retriving the image from the database, again convert the byte array to image.
C#
public Image byteArrayToImage(byte[] byteArrayIn)
{
     MemoryStream ms = new MemoryStream(byteArrayIn);
     Image returnImage = Image.FromStream(ms);
     return returnImage;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900