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));
}
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
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With