SQL Server IMAGE DataType to PictureBox

The following sample is great if you want to load an Employee or signature image from your database. I tried to comment it as much as possible so I think the code will be self explanatory.

 

// Load an image into a PictureBox from a SQL Server image datatype

public void LoadImage(PictureBox pic)

{

    // TODO: change connection string

    SqlConnection con = new SqlConnection(“Data Source=<server>; Initial Catalog=<YouDatabaseName>; Integrated Security=SSPI;”);

    // TODO: change query to pull form your own tables

    SqlCommand cmd = new SqlCommand(“select top 1 signature_jpeg from SignOffForm where order_id = @order_id”, con);

    SqlDataReader rdr = null;

    byte[] imgData = null;

    try

    {

        int orderID = 10000;

        cmd.Parameters.AddWithValue(“@order_id”, orderID);

 

        con.Open();

        rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

        if (rdr.Read())

        {

            // make sure our byte array is big enough to store the image

            imgData = new byte[rdr.GetBytes(0, 0, null, 0, int.MaxValue)];

            // retrieve the image from the datareader and store it in a byte array

            rdr.GetBytes(0, 0, imgData, 0, imgData.Length);

            // use a memorystream to read the image

            MemoryStream ms = new MemoryStream(imgData);

            // set the image to the picturebox

            pic.Image = Image.FromStream(ms);

        }

        else

        {

            MessageBox.Show(“No records found in the database.”, “Warning”);

        }

    }

    catch (Exception ex)

    {

        MessageBox.Show(ex.ToString(), “Error”);

    }

    finally

    {

        if (con.State == ConnectionState.Open) con.Close();

    }

}

Leave a Reply