Hello Experts

Here is my connection string

string con = "Data source =YS-8462BA359936;Initial Catalog = Schooldata;Integrated Security = True";

and my store procedure is

SqlConnection objCon = new SqlConnection(con);
                objCon.Open();

                SqlCommand cmd = new SqlCommand("Studentinsertadmission", objCon);
  cmd.Parameters.Add(new SqlParameter("@Studentid",Convert.ToInt32( studentid.Text)));
                cmd.Parameters.Add(new SqlParameter("@StudentName", firstname.Text));
                cmd.Parameters.Add(new SqlParameter("@Image", image.image  ));


cmd.CommandType = CommandType.StoredProcedure;
                int rows = cmd.ExecuteNonQuery();
                objCon.Close();
                
                MessageBox.Show("Record Inserted Successfully! ");

But i am not able to load picture in picture box and also save in sql database
Please Solve my Problem
Thanks

Hi, check here.

Remember you have to get Byte array (byte[]) from picture to save it into a dataBase.

Hello Sir Mitja I already visited this cite and could not understand.But I Always Understand of Your Code Because it always simple and perfect.So Please Tell Me and solved my problem.

Thanks

What is your DB table (table you wish to insert into) structure?

Anyway, here is my solution for you, I only didnt include sql and DB insertion.
(for it you have to use sql query:
@"INSERT INTO Table VALUE (@id, @picByte, @picName)"
- id
- pic byte[]
- pic name (string) - its optional, but its good to have it.

So heres the code:

string lastDir;
        string fileName;
        public Form1()
        {
            InitializeComponent();
        }

        private void buttonOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog open = new OpenFileDialog();
            open.Filter = "Image Files(*.png; *.jpg; *.bmp)|*.png; *.jpg; *.bmp";
            if (lastDir == null)            
                open.InitialDirectory = @"C:\";
            else
                open.InitialDirectory = lastDir;
            if (open.ShowDialog() == DialogResult.OK)
            {
                fileName = System.IO.Path.GetFullPath(open.FileName);
                lastDir = open.FileName;
                pictureBox1.Image = new Bitmap(open.FileName);
                this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
            }
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            //get image:
            Image img = Image.FromFile(fileName);
            //get byte array from image:
            byte[] byteImg = ImageToByteArray(img);

            //here do the insertion into dataBase!
            //but remember, your field in DB must be type to byte array
        }

        public byte[] ImageToByteArray(Image img)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            return ms.ToArray();
        }

Ok, that you wont bother with insert query (even if you know it, or if you have a stored procedure), here is my full code:

string lastDir;
        string fileName;
        public Form1()
        {
            InitializeComponent();
        }

        private void buttonOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog open = new OpenFileDialog();
            open.Filter = "Image Files(*.png; *.jpg; *.bmp)|*.png; *.jpg; *.bmp";
            if (lastDir == null)            
                open.InitialDirectory = @"C:\";
            else
                open.InitialDirectory = lastDir;
            if (open.ShowDialog() == DialogResult.OK)
            {
                fileName = System.IO.Path.GetFullPath(open.FileName);
                lastDir = open.FileName;
                pictureBox1.Image = new Bitmap(open.FileName);
                this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
            }
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            //get image:
            Image img = Image.FromFile(fileName);
            //get byte array from image:
            byte[] byteImg = ImageToByteArray(img);

            //here do the insertion into dataBase!
            //but remember, your field in DB must be type to byte array
            //example:
            using (SqlConnection sqlConn = new SqlConnection("connString"))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = @"INSERT INTO MyTable VALUES (@id, @image, @name)";
                    cmd.Connection = sqlConn;
                    sqlConn.Open();
                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
        }

        public byte[] ImageToByteArray(Image img)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            return ms.ToArray();
        }
commented: Mitja is best developer +3

Ok My Database name is Imagetable and In this table there are
Pictureid Int Picturename varchar(50)PictureImage
My store Procedure is

creatset ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


ALTER procedure [dbo].[imageinsert]
@pictureid int,
@picturename varchar(50),
@picture Image

As 
Begin
insert Imagetable(Pictureid,picturename,picture)
Values (@pictureid,@picturename,@picture)
end

Now Please Help Me.

Ok Sir Mitja its was my fault i was not understanding Your point.now It Problem has been solved the code is under

Pictureid int
picturevarbinary(Max)

and c# code is

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 StoreImagesInSQLServer
{
    public partial class frmNewImage : Form
    {
        public frmNewImage()
        {
            InitializeComponent();
        }

        private void cmdSave_Click(object sender, EventArgs e)
        {
            try
            {
                //Read Image Bytes into a byte array
                byte[] imageData = ReadFile(txtImagePath.Text);
                
                //Initialize SQL Server Connection
                SqlConnection CN = new SqlConnection(txtConnectionString.Text);

                //Set insert query
                string qry = "insert into Imageform(Picture) values(@Picture)";
               

                //Initialize SqlCommand object for insert.
                SqlCommand SqlCom = new SqlCommand(qry, CN);

                //We are passing Original Image Path and Image byte data as sql parameters.
               /* SqlCom.Parameters.Add(new SqlParameter("@OriginalPath", (object)txtImagePath.Text));
                * */
                SqlCom.Parameters.Add(new SqlParameter("@Picture", (object)imageData));

                //Open connection and execute insert query.
                CN.Open();
                SqlCom.ExecuteNonQuery();
                CN.Close();

                //Close form and return to list or images.
                this.Close();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message );
            }
        }

        private void cmdBrowse_Click(object sender, EventArgs e)
        {
            //Ask user to select file.
            OpenFileDialog dlg = new OpenFileDialog();
            DialogResult dlgRes = dlg.ShowDialog();
            if (dlgRes != DialogResult.Cancel)
            {
                //Set image in picture box
                pictureBox1.ImageLocation = dlg.FileName;

                //Provide file path in txtImagePath text box.
                txtImagePath.Text = dlg.FileName;
            }
        }

        //Open file in to a filestream and read data in a byte array.
        byte[] ReadFile(string sPath)
        {
            //Initialize byte array with a null value initially.
            byte[] data = null;

            //Use FileInfo object to get file size.
            FileInfo fInfo = new FileInfo(sPath);
            long numBytes = fInfo.Length;

            //Open FileStream to read file
            FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);

            //Use BinaryReader to read file stream into byte array.
            BinaryReader br = new BinaryReader(fStream);

            //When you use BinaryReader, you need to supply number of bytes to read from file.
            //In this case we want to read entire file. So supplying total number of bytes.
            data = br.ReadBytes((int)numBytes);
            return data;
        }

        private void cmdCancel_Click(object sender, EventArgs e)
        {
            //Close this form if user clicks cancel.
            this.Close();
        }
    }
}
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 StoreImagesInSQLServer
{
    public partial class frmImagesStore : Form
    {
        public frmImagesStore()
        {
            InitializeComponent();
        }

        //Get table rows from sql server to be displayed in Datagrid.
        void GetImagesFromDatabase()
        {
            try
            {
                //Initialize SQL Server connection.
                SqlConnection CN = new SqlConnection(txtConnectionString.Text);

                //Initialize SQL adapter.
                SqlDataAdapter ADAP = new SqlDataAdapter("Select * from Imageform", CN);

                //Initialize Dataset.
                DataSet DS = new DataSet();

                //Fill dataset with ImagesStore table.
                ADAP.Fill(DS, "Picture");

                //Fill Grid with dataset.
                dataGridView1.DataSource = DS.Tables["Picture"];
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void cmdConnect_Click(object sender, EventArgs e)
        {
            //Fill datagrid with table rows.
            GetImagesFromDatabase();
        }

        //Open form to get new image file.
        private void cmdStoreNewImage_Click(object sender, EventArgs e)
        {
            frmNewImage fNew = new frmNewImage();
            //Supply connection string from this form to frmNewImage form.
            fNew.txtConnectionString.Text = txtConnectionString.Text;
            fNew.ShowDialog();

            //Refresh Image
            cmdConnect_Click(null, null);
        }

        //When user changes row selection, display image of selected row in picture box.
        private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                //Get image data from gridview column.          /////////Here Change imageform to picture/////
                byte[] imageData = (byte[])dataGridView1.Rows[e.RowIndex].Cells["Picture"].Value;

                //Initialize image variable
                Image newImage;
                //Read image data into a memory stream
                using (MemoryStream ms = new MemoryStream(imageData, 0, imageData.Length))
                {
                    ms.Write(imageData, 0, imageData.Length);

                    //Set image variable value using memory stream.
                    newImage = Image.FromStream(ms, true);
                }

                //set picture
                pictureBox1.Image = newImage;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void frmImagesStore_Load(object sender, EventArgs e)
        {

        }
        
    }
}

This Thread is Solved
Thanks to all Experts specially Mitja

:)
you are welcome mate.
Since you are a nice guy I really like to do the code for you. So be it in the future too.
bye, bye

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.