How to load image from SQL Server into picture box?

You never uploaded the image contents to the database. That’s just the file name.

Say, as an example, that you have a file path to work with (it seems you do, given the question’s contents). In your application, you would upload this to the database following this format:

byte[] image = File.ReadAllBytes("D:\\11.jpg");

SqlCommand sqlCommand = new SqlCommand("INSERT INTO imageTest (pic_id, pic) VALUES (1, @Image)", yourConnectionReference);
sqlCommand.Parameters.AddWithValue("@Image", image);
sqlCommand.ExecuteNonQuery();

Please bear in mind that your pic field will more than likely need to change data type. A common type for this information is VARBINARY.

The next part is reading the file into a PictureBox. For this, you’ll need to SELECT the data out:

SqlDataAdapter dataAdapter = new SqlDataAdapter(new SqlCommand("SELECT pic FROM imageTest WHERE pic_id = 1", yourConnectionReference));
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);

if (dataSet.Tables[0].Rows.Count == 1)
{
    Byte[] data = new Byte[0];
    data = (Byte[])(dataSet.Tables[0].Rows[0]["pic"]);
    MemoryStream mem = new MemoryStream(data);
    yourPictureBox.Image= Image.FromStream(mem);
} 

And that should be about it. You might want to do better safety checks, but this should help you get started.

Leave a Comment