Windows Forms: How to Save and Retrieve Image from SQL database in C#

By FoxLearn 8/13/2017 8:25:10 AM   19.22K
How to save and retrieve image from SQL database using C#

Step 1Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "SaveImageToDatabase" and then click OK

save image to sql databaseStep 2: Design your form as below

save image to sql database in c#

Step 3: Create a MyPicture table, then add to EF Model as below

entity framework model

Step 4: Add code to handle your form as below

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SaveImageToDatabase
{
    public partial class Form1 : Form
    {
        string fileName;
        List<MyPicture> list;
        public Form1()
        {
            InitializeComponent();
        }

        //Convert binary to image
        Image ConvertBinaryToImage(byte[] data)
        {
            using(MemoryStream ms = new MemoryStream(data))
            {
                return Image.FromStream(ms);
            }
        }

        private void listView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView.FocusedItem != null)
            {
                //Set image to picture box
                pictureBox.Image = ConvertBinaryToImage(list[listView.FocusedItem.Index].Data);
                lblFilename.Text = listView.FocusedItem.SubItems[0].Text;
            }
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            //Read image file
            using(OpenFileDialog ofd = new OpenFileDialog() { Filter = "JPEG|*.jpg", ValidateNames = true, Multiselect = false })
            {
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    fileName = ofd.FileName;
                    lblFilename.Text = fileName;
                    pictureBox.Image = Image.FromFile(fileName);
                }
            }
        }

        //Convert image to binary
        byte[] ConvertImageToBinary(Image img)
        {
            using(MemoryStream ms = new MemoryStream())
            {
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                return ms.ToArray();
            }
        }

        private async void btnSave_Click(object sender, EventArgs e)
        {
            //Save image to sql database using entity framework, async
            using(PicEntities db = new PicEntities())
            {
                MyPicture pic = new MyPicture() { FileName = fileName, Data = ConvertImageToBinary(pictureBox.Image) };
                db.MyPictures.Add(pic);
                await db.SaveChangesAsync();
                MessageBox.Show("You have been successfully saved.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            listView.Items.Clear();
            //Load image from sql database to listview
            using(PicEntities db = new PicEntities())
            {
                list = db.MyPictures.ToList();
                foreach(MyPicture pic in list)
                {
                    ListViewItem item = new ListViewItem(pic.FileName);
                    listView.Items.Add(item);
                }
            }
        }
    }
}

VIDEO TUTORIALS