Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading PictureBox Image From Database

Tags:

c#

sql-server

i'm trying to load images from database to a PictureBox. I use these following codes in order to load them to my picture. I've written some code but don't know what I should do for continuing.

Any help will be appreciated.

private void button1_Click(object sender, EventArgs e)
    {
        sql = new SqlConnection(@"Data Source=PC-PC\PC;Initial Catalog=Test;Integrated Security=True");
        cmd = new SqlCommand();
        cmd.Connection = sql;
        cmd.CommandText = ("select Image from Entry where EntryID =@EntryID");
        cmd.Parameters.AddWithValue("@EntryID", Convert.ToInt32(textBox1.Text));
    }
like image 234
aliprogrammer Avatar asked May 04 '12 18:05

aliprogrammer


2 Answers

Assuming we have a simple database with a table called BLOBTest:

CREATE TABLE BLOBTest
(
BLOBID INT IDENTITY NOT NULL,
BLOBData IMAGE NOT NULL
)

We could retrieve the image to code in the following way:

try
{
    SqlConnection cn = new SqlConnection(strCn);
    cn.Open();

    //Retrieve BLOB from database into DataSet.
    SqlCommand cmd = new SqlCommand("SELECT BLOBID, BLOBData FROM BLOBTest ORDER BY BLOBID", cn);   
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds, "BLOBTest");
    int c = ds.Tables["BLOBTest"].Rows.Count;

    if(c>0)
    {   //BLOB is read into Byte array, then used to construct MemoryStream,
        //then passed to PictureBox.
        Byte[] byteBLOBData =  new Byte[0];
        byteBLOBData = (Byte[])(ds.Tables["BLOBTest"].Rows[c - 1]["BLOBData"]);
        MemoryStream stmBLOBData = new MemoryStream(byteBLOBData);
        pictureBox1.Image= Image.FromStream(stmBLOBData);
    } 
    cn.Close();
}
catch(Exception ex)
{MessageBox.Show(ex.Message);}

This code retrieves the rows from the BLOBTest table in the database into a DataSet, copies the most recently added image into a Byte array and then into a MemoryStream object, and then loads the MemoryStream into the Image property of the PictureBox control.

Full reference guide:

http://support.microsoft.com/kb/317701

like image 83
GoRoS Avatar answered Nov 14 '22 21:11

GoRoS


Continue with something like this in the button1_Click:

// Your code first, here.

var da = new SqlDataAdapter(cmd);
var ds = new DataSet();
da.Fill(ds, "Images");
int count = ds.Tables["Images"].Rows.Count;

if (count > 0)
{ 
    var data = (Byte[])ds.Tables["Images"].Rows[count - 1]["Image"];
    var stream = new MemoryStream(data);
    pictureBox1.Image = Image.FromStream(stream);
} 
like image 16
Mario S Avatar answered Nov 14 '22 22:11

Mario S