SOTHIK-Vicheachann
SOTHIK-Vicheachann

Reputation: 55

How to insert PictureBox to Sql Server Database Varbinary(MAX) with C#?

I have a table that have a field as Varbinary(MAX) datatype and I want to insert image file from PictureBox into this column. So how can I convert and insert image to Varbinary in Sql Server. Thank for help me.

Upvotes: 3

Views: 1921

Answers (1)

Nino
Nino

Reputation: 7095

You should really show some code, what have you tried...

This is only a guess, but it should give you a clue how to insert picture into database:

//byte array that will hold image data
byte[] imageData = null;

using (var ms = new MemoryStream())
{
    //here is image property of your pictureBox control  saved into memory stream
    pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
    imageData = ms.ToArray();
}

//make sql connection
SqlConnection conn = new SqlConnection("your connection string goes here");
// command with parameter
SqlCommand cmd = new SqlCommand("insert into TableWithImages (imageData) values (@imageData);", conn);
//define param and pass byte array as value
cmd.Parameters.Add("@imageData", SqlDbType.VarBinary).Value = imageData;

//do insert
cmd.ExecuteNonQuery();

Upvotes: 2

Related Questions