Introduction
This tip shows you how to insert an image in database. It is a basic and simple method to store an image in SQL Server database.
First, create a table named image
in database using the following code:
CREATE TABLE [dbo].[image](
[img] [image] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
Open a new form in Visual Studio:
- Get a
groupbox
. - Insert a picture box inside
groupbox
. - Set
dock
property of picturebox
to fill
. - The code for upload image in
picturebox
is as follows:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog fop = new OpenFileDialog();
fop.InitialDirectory = @"C:\";
fop.Filter = "[JPG,JPEG]|*.jpg";
if (fop.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(fop.FileName);
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.Refresh();
}
}
- The code for save button to save image in database is as follows:
string strConn = "Data Source= System Name;
Initial Catalog=Database Name; User Id=your user id; Password= your password";
SqlConnection Con = new SqlConnection(strConn);
Con.Open();
string strCmd = "insert into image (img) values ('" + pictureBox1.Image + "' )" ;
SqlCommand Cmd = new SqlCommand(strCmd, Con);
SqlDataAdapter da = new SqlDataAdapter(strCmd, Con);
DataSet ds = new DataSet();
Cmd.ExecuteNonQuery();
MessageBox.Show("success");
Con.Close();