Click here to Skip to main content
15,881,380 members
Articles / Programming Languages / C#
Article

Sending/Receiving PictureBox Image in C# To/From Microsoft SQL SERVER

Rate me:
Please Sign up or sign in to vote.
4.53/5 (37 votes)
10 May 2008CPOL 175.3K   66   30
This article is written for those stuck in such a problem
Image 1

Image 2

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!

C#
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;

//author:Morteza Naeimabadi  Location=IRAN ,Yazd
//written in 2008/03/12

namespace SampleOfMorteza
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //We are using SQL express.
            //My database name is "PictureDb".
            SqlConnection con = new SqlConnection
                               ("Server=.;database=PictureDb;integrated security=true");
            //I have used a table named "tblUsers" and fill the fields
            SqlCommand com = new SqlCommand("insert into tblUsers
                            (fldCode,fldPic) values(1,@Pic)", con);

            //In here, I have to save the picturebox image to tblUsers
            //because you were not able to send the PictureBox1.Image
            //to field "fldPic" that is of kind
            //"image" in SQL SERVER EXPRESS, then you should do something else
            // and that is converting
            //your picture box image to an array of bytes and then sending
            //that array to database.
            //Below, we have used a stream which will be used to
            //contain our picturebox image bytes.
            MemoryStream stream=new MemoryStream();
            //through the instruction below, we save the
            //image to byte in the object "stream".
            pictureBox1.Image.Save(stream,System.Drawing.Imaging.ImageFormat.Jpeg);

            //Below is the most important part, actually you are
            //transferring the bytes of the array
            //to the pic which is also of kind byte[]
            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);
            //for retrieving the image field in SQL SERVER EXPRESS
            //Database you should first bring
            //that image in DataList or DataTable
            //then add the content to the byte[] array.
            //That's ALL!
            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);
            //With the code below, you are in fact converting the byte array of image
            //to the real image.
            pictureBox2.Image = Image.FromStream(stream);
        }
    }
}

History

  • 11th May, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Iran (Islamic Republic of) Iran (Islamic Republic of)
independent IT Consultant,Currently engaged with Sharepoint developing and MVC Asp.net apps

Comments and Discussions

 
Answersuperb code... Pin
p.rosekumar29-Oct-19 3:52
p.rosekumar29-Oct-19 3:52 
GeneralMy vote of 5 Pin
CyberSaint3-May-17 5:27
professionalCyberSaint3-May-17 5:27 
QuestionParameter is invalid Pin
Member 1061618425-Sep-14 20:50
Member 1061618425-Sep-14 20:50 
AnswerRe: Parameter is invalid Pin
Kiran R S12-Apr-15 21:11
Kiran R S12-Apr-15 21:11 
Questiontype of fldPic Pin
CP-Ayyub12-Apr-14 2:33
CP-Ayyub12-Apr-14 2:33 
AnswerRe: type of fldPic Pin
Kiran R S12-Apr-15 21:12
Kiran R S12-Apr-15 21:12 
QuestionThanks Pin
Garima111115-Aug-13 21:02
Garima111115-Aug-13 21:02 
Questionsearching by image Pin
Rahul Kumar Ghosh20-Apr-13 18:14
Rahul Kumar Ghosh20-Apr-13 18:14 
QuestionSome advises: Pin
Shahin Khorshidnia23-Dec-12 3:00
professionalShahin Khorshidnia23-Dec-12 3:00 
QuestionParameter is not valid Pin
groupnima19-Oct-12 10:06
groupnima19-Oct-12 10:06 
AnswerRe: Parameter is not valid Pin
Morteza Naeiamabadi21-Oct-12 3:10
Morteza Naeiamabadi21-Oct-12 3:10 
QuestionTHANK YOU!! THANK YOU!! THANK YOU!! THANK YOU!! THANK YOU!! Pin
Scott A Parker25-May-12 8:31
Scott A Parker25-May-12 8:31 
Several days of banging my head against a brick wall solved in just a few min!Thumbs Up | :thumbsup:
AnswerRe: THANK YOU!! THANK YOU!! THANK YOU!! THANK YOU!! THANK YOU!! Pin
Morteza Naeiamabadi26-May-12 4:08
Morteza Naeiamabadi26-May-12 4:08 
Questionquestion2 Pin
aliprogrammer27-Apr-12 3:07
aliprogrammer27-Apr-12 3:07 
AnswerRe: question2 Pin
Morteza Naeiamabadi27-Apr-12 4:33
Morteza Naeiamabadi27-Apr-12 4:33 
GeneralRe: question2 Pin
aliprogrammer28-Apr-12 20:19
aliprogrammer28-Apr-12 20:19 
Questionquestion Pin
aliprogrammer27-Apr-12 2:56
aliprogrammer27-Apr-12 2:56 
AnswerRe: question Pin
Morteza Naeiamabadi27-Apr-12 4:31
Morteza Naeiamabadi27-Apr-12 4:31 
GeneralRe: question Pin
aliprogrammer28-Apr-12 20:17
aliprogrammer28-Apr-12 20:17 
GeneralMy vote of 5 Pin
jalalbabaei17-Mar-12 19:37
jalalbabaei17-Mar-12 19:37 
QuestionGOOOOOOOD Pin
balagp14-Jan-12 3:43
balagp14-Jan-12 3:43 
AnswerRe: GOOOOOOOD Pin
Morteza Naeiamabadi27-Apr-12 4:35
Morteza Naeiamabadi27-Apr-12 4:35 
Questionamir Pin
amir 214-Jul-11 22:53
amir 214-Jul-11 22:53 
QuestionThanks Pin
mahmood seyedkarimi27-Jun-11 0:07
mahmood seyedkarimi27-Jun-11 0:07 
GeneralMy vote of 5 Pin
Ivan Tanasijevic27-Oct-10 5:01
Ivan Tanasijevic27-Oct-10 5:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.