How to Save Image in database and display in PictureBox Using C#

By
Hi Friends ! Today ,I will show you "How to save image in Database and display it in Picture Box control in Windows Forms Application".Here I will create a Browse Dialog Box ,which will helpful to select an image and save in Picture Box Control from your system. In this i will   display the image in Picture Box control from Sql database table using c#. You can easily use this concepts in your applications.If you understand, this whole concepts then you can  make any windows forms application easily.I have putted some restrictions also,means you can't upload image size 25 KB and signature size 12 KB in this application. If you want you can add some extra features also in this application which are given below:-
  • You can Add Preview and printout concepts in this application from here.
  • You create setup file,follow steps from here.
  • You can create setup file with Sql database and install it any client machine ,follow steps from here.
There are some steps to implement this whole concepts in your Windows forms application which are given below:-
Step 1:-First open your visual studio --> File -->New --> Project...--->Select Widows Forms Application -->OK-->Open Solution Explorer --> Add New Window Form(Form1.cs[Design]) by right click on Your project-->Drag and Drop label ,TextBox and Button controls on the Form as shown below:-

design

Step 2:- Now open Solution Explorer -->Add another Window Form (Form2.cs[Design])--> Drag and Drop Table Layout Panel ,label,Picture Box and Button controls as shown below:-


design

Step 3:-Now again open Solution Explorer -->Add another Window Form (Form3.cs[Design])--> Drag and Drop label,TextBox,Picture Box and Button controls as shown below:-


design

Step 4:- Now open Form1.cs[Design] --> Double click on Browse (Button 2,Button 3) and Proceed (Button 1) Button -->Write the c# codes as given below:-
using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace database_image
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        OpenFileDialog fd1 = new OpenFileDialog();
        private void button2_Click(object sender, EventArgs e)
        {
            fd1.Filter = "image files|*.jpg;*.png;*.gif;*.icon;.*;";
            DialogResult dres1 = fd1.ShowDialog();
            if (dres1 == DialogResult.Abort)
                return;
            if (dres1 == DialogResult.Cancel)
                return;
            textBox4.Text = fd1.FileName;
        }
        OpenFileDialog fd2 = new OpenFileDialog();
        private void button3_Click(object sender, EventArgs e)
        {  
            fd2.Filter = "image files|*.jpg;*.png;.*gif;*.icon;.*;";
            DialogResult dres2 = fd2.ShowDialog();
            if (dres2 == DialogResult.Abort)
                return;
            if (dres2 == DialogResult.Cancel)
                return;
            textBox5.Text = fd2.FileName;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 f2 = new Form2();
            this.Hide();
            f2.label6.Text = textBox1.Text.ToString();
            f2.label7.Text = textBox2.Text.ToString();
            f2.label8.Text = textBox3.Text.ToString();
            f2.pictureBox1.Image = Image.FromFile(fd1.FileName);
            MemoryStream ms1 = new MemoryStream();
            f2.pictureBox1.Image.Save(ms1, System.Drawing.Imaging.ImageFormat.Jpeg);
            //MessageBox.Show(ms1.Length.ToString()); calculate image length
            f2.pictureBox2.Image = Image.FromFile(fd2.FileName);
            MemoryStream ms2 = new MemoryStream();
            f2.pictureBox1.Image.Save(ms2, System.Drawing.Imaging.ImageFormat.Jpeg);
            if (ms1.Length>25600  && ms2.Length > 12228)
                MessageBox.Show("Please upload less than 25 kb image and less than 12 kb Signature");
            else
            f2.Show();
        }
    }
}

Descriptions:-
  • Here i have used  Browse (Button 2,Button 3) dialog Box control ,to select an image and save in Picture Box Control from your system
  • Proceed (Button 1) Button control is used to transfer the TextBox values From  Form1 .cs[Design page] to Form2 .cs[Design page]. It will also check whether image and signature size is less than 25 and 12 KB or not.
  • If user Upload image and signature size greater than 25 and 12 KB respectively ,Then it will show error message.I will show it latter.
Step 5:- Now open Form 2 .cs[Design] -->Right click on each controls( label6, label7, label8, PictureBox1 and PictureBox2) --> Set Modifier = Public as shown below:-


modifier_public
Note :- When you set Modifier = Public then you can access that control's data from the Form 1 otherwise it will show error  inaccessible control.
Step 6:- Now Open your Sql server Management studio-->Create a table (student_records) -add some required columns as shown below:-


student_records

Step 7:- Now write Following  c# codes on Save and Verify Details Button clicks as given below:-
using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;

namespace database_image
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            MemoryStream ms1 =new MemoryStream();
            MemoryStream ms2 =new MemoryStream();
            pictureBox1.Image.Save(ms1,System.Drawing.Imaging.ImageFormat.Jpeg);
            pictureBox2.Image.Save(ms2,System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] img_arr1 =new byte[ms1.Length];
            byte[] img_arr2 =new byte[ms2.Length];
            ms1.Read(img_arr1,0, img_arr1.Length);
            ms2.Read(img_arr2,0, img_arr2.Length);
           SqlConnection con = new SqlConnection("data source=RAMASHANKER-PC;Integrated Security=Yes;Database=master");
           con.Open();
           SqlCommand cmd = new SqlCommand("insert into student_records(name,qualification,age,image,signature)values(@a,@b,@c,@d,@e)", con);
            cmd.Parameters.AddWithValue("@a", label6.Text);
            cmd.Parameters.AddWithValue("@b", label7.Text);
            cmd.Parameters.AddWithValue("@c", label8.Text);
            cmd.Parameters.AddWithValue("@d",img_arr1);
            cmd.Parameters.AddWithValue("@e", img_arr2);
            int result = cmd.ExecuteNonQuery();
            if (result > 0)
                MessageBox.Show("Data inserted successfully");
            else
                MessageBox.Show("Data is not inserting in database");
            con.Close();      
        }
        private void button3_Click(object sender, EventArgs e)
        {
            Form3 f3 = new Form3();
            Form2 f2 = new Form2();
            f2.Hide();
            f3.Show();
        }  
    }
}

Descriptions:-
  • When you will click save Button then data will be stored in sql database (student_records table).
  • When you click verify Details then form 2 will be hide and Form 3 will be showed.
Step 8:- Now open Form 3.cs [Design] --> Right click on each control (PictureBox1, PictureBox2) -->Set Modifier = Public as shown below:-

modifier_public

Note :- When you set Modifier = Public then you can access that control's data from the Form 2 otherwise it will show  error inaccessible control. 
Step 9:- Now Write the c# codes on Submit button click as given below:-
using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;

namespace database_image
{
    public partial class Form3 : Form
    {
        public Form3()
        {
            InitializeComponent();
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection("data source=RAMASHANKER-PC;Integrated Security=Yes;Database=master");
            con.Open();
            
            SqlCommand cmd = new SqlCommand("select signature from student_records where name='"+textBox1.Text+"'", con);
            try
            {

                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.Read())
                {
                    byte[] img_arr1 = (byte[])dr["image"];
                    byte[] sig_arr2 = (byte[])dr["signature"];
                    MemoryStream ms1 = new MemoryStream(img_arr1);
                    MemoryStream ms2 = new MemoryStream(sig_arr2);
                    ms1.Seek(0, SeekOrigin.Begin);
                    ms2.Seek(0, SeekOrigin.Begin);
                    pictureBox1.Image = Image.FromStream(ms1);
                    pictureBox2.Image = Image.FromStream(ms2);
                }
                else
                {
             MessageBox.Show("Your Data is not inserted in database try again");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                con.Close();
            }
        }    
    }
}

Descriptions:-
Here i have fetched image and signature values from the sql database(student_records) and showed the pictures (image,signature)in PictureBox Control on Form 3 page .I have used try catch and finally block concepts also,for more visit here.
Step 10:- Now Run the Application(press F5) -->Enter Text Fields Details -->Upload the image and Signature less than 25 and 12 KB respectively as shown below:-


details

Step 11:- Now Click Proceed Button -->You will see following output as shown below:-


details

Step 12:- If User will enter  any  image and signature values greater than 25 and 12 KB respectively ,this application will show an error as shown below:-


error

Step 13:-Now Click Save Button -->You will see the following output as shown below:-

data_inserted

Step 14:-Now Click Verify Details Button -->Enter required fields details -->press Submit Button --> You will see following output as shown below:-


fetch values

For More...
  1. How to host asp.net website on server free
  2. Stored Procedure in sql server
  3. How to generate unique number and store in database
  4. Real time Ado.net application 
  5. How to implement WCF Service in asp.net application
  6. How to implement authentication concepts in asp.net application
  7. How to implement form based authentication in asp.net application
  8. How to implement web services in asp.net application
  9. How to implement caching concepts in asp.net application
  10. How to insert ,edit,update,delete and print operation in asp.net
  11. How to implement cookie in asp.net application
  12. How to implement validation controls in asp.net application
  13. How to implement views in ms sql server
  14. How to implement Navigation control in asp.net
  15. How implement multiple main method in c#
I hope this helpful for you.
In coming tutorial,i will explain this concepts on web(asp.net) also.
Download whole attached file  
       Download

12 comments:

  1. byte[] img_arr1 = (byte[])dr["image"];
    IndexOutofRange Exception occures

    ReplyDelete
  2. its not working,show error parameter invalid

    ReplyDelete
  3. its not working,show error parameter invalid

    ReplyDelete
  4. It is possible to access form2 control like lable ,textbox in form1.

    ReplyDelete
  5. i am facing proble in this article can not be accessed form2 control in form1 proceed button.

    ReplyDelete
  6. "cmd.Parameters.AddWithValue("@d",img_arr1);
    cmd.Parameters.AddWithValue("@e", img_arr2); "
    error in storing image.. Its not storing the array of byte code.
    replace img_arr1 and img_arr2 with ms1.ToArray() and ms2.ToArray() it will work...

    ReplyDelete
  7. sir pls help me solve this qns
    How to get image source from database and how to display this image in the container

    ReplyDelete
  8. I have a problem.I am using xampp sql server.Would you please give me the required sql file for that or tell me how to modify my code if i input image as medium blob.

    ReplyDelete
  9. Thanks ..I have no problem..Please provide more window and web codes ...

    ReplyDelete

Powered by Blogger.