Introduction
This article is intended to fulfill the lack of clarity in retrieving and sending PictureBox
images or let's say any image in a Windows application to a database and vice versa. So guys, don't panic, just relax because the code is so simple.
Background
I will advice those guys who are still not familiar with the SQL language and broadly speaking, those not having database interaction knowledge in Windows application in .NET to leave this page and go after those mentioned items.
Using the Code
The entire code with comments in each line is shown below. Enjoy it!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
namespace SampleOfMorteza
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection
("Server=.;database=PictureDb;integrated security=true");
SqlCommand com = new SqlCommand("insert into tblUsers
(fldCode,fldPic) values(1,@Pic)", con);
MemoryStream stream=new MemoryStream();
pictureBox1.Image.Save(stream,System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] pic=stream.ToArray();
com.Parameters.AddWithValue("@Pic", pic);
try
{
con.Open();
com.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
private void button2_Click(object sender, EventArgs e)
{
SqlConnection connect = new SqlConnection
("Server=.;database=PictureDb;integrated security=true");
SqlCommand command = new SqlCommand
("select fldPic from tblUsers where fldCode=1", connect);
SqlDataAdapter dp = new SqlDataAdapter(command);
DataSet ds = new DataSet("MyImages");
byte[] MyData = new byte[0];
dp.Fill(ds, "MyImages");
DataRow myRow;
myRow = ds.Tables["MyImages"].Rows[0];
MyData = (byte[])myRow["fldPic"];
MemoryStream stream = new MemoryStream(MyData);
pictureBox2.Image = Image.FromStream(stream);
}
}
}
History
- 11th May, 2008: Initial post