How to retrieve image from database using C#

This C# program explain how you can retrieve images from SQL Server Database. First you need to Create New Project and give the Name of the project is RetrieveImageFromDataBase Add the label, TextBox, command button and picture box control and copy this code and paste. So please change the data source name, database name and Table name.
Please Give the Comments.
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.Data.SqlClient;
usingSystem.IO;
namespaceRetrieveImageFromDataBase
{
    public partial class Form1 : Form
    {
        publicForm1()
        {
            InitializeComponent();
        }
        privatevoid button1_Click(objectsender, EventArgs e)
        {
            SqlConnectioncon = new SqlConnection(“Data Source=localhost;Initial Catalog=DataBaseName;Integrated Security=True”);
           
            con.Open();
            stringsql = “Select Photo from Employee where CustId=” + textBox1.Text +“”;
            SqlDataAdapterdadata = new SqlDataAdapter(sql,con);
            DataSetdsdata = new DataSet(“Employee”);
            dadata.Fill(dsdata, “Employee”);
            intcnt = dsdata.Tables[0].Rows.Count;
            if(cnt > 0)
            {
                byte[] Imgdata = (byte[])dsdata.Tables[0].Rows[0][“photo”];
                MemoryStreamDataStream = new MemoryStream(Imgdata);
                pictureBox1.Image = new Bitmap(DataStream);
            }
             
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *