Insert Images In DataGridView In Windows Application Using C#

We use PictureBox control to add pictures and then that picture will get inserted into the DataGridView.

Initial chamber

Step 1: Open Visual Studio 2010, Go to File, New, Projects and under Visual C# select Windows.

Windows Application

You can change the name of the project and browse your project to different location too. And then press – OK.

Design chamber

Step 2: Now open your Form1.cs file, where we create our design for DataGridView and Picture Image Control. We will drag a PictureBox, a button, and a DataGridView from toolbox to Form1.cs. You will see your Form look like this.

Form1.cs [Design]

design

Code chamber

Right Click on the blank part of Form1.cs and View Code. You will see you are entered in the code part of the form. Write the following code for Form1.cs.

Form1.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9. using System.IO;  
  10. namespace WindowsFormsApplication4  
  11. {  
  12.     public partial class Form1 : Form  
  13.     {  
  14.         public Form1()  
  15.         {  
  16.             InitializeComponent();  
  17.         }  
  18.   
  19.         private void pictureBox1_Click(object sender, EventArgs e)  
  20.         {  
  21.             OpenFileDialog opnfd = new OpenFileDialog();  
  22.             opnfd.Filter = "Image Files (*.jpg;*.jpeg;.*.gif;)|*.jpg;*.jpeg;.*.gif";  
  23.             if (opnfd.ShowDialog() == DialogResult.OK)  
  24.             {  
  25.                 pictureBox1.Image = new Bitmap(opnfd.FileName);  
  26.   
  27.             }  
  28.   
  29.         }  
  30.   
  31.         private void button1_Click(object sender, EventArgs e)  
  32.         {  
  33.             MemoryStream mmst = new MemoryStream();  
  34.             pictureBox1.Image.Save(mmst, pictureBox1.Image.RawFormat);  
  35.             byte[] img = mmst.ToArray();  
  36.             dataGridView1.Rows.Add(img);  
  37.         }  
  38.   
  39.         private void Form1_Load(object sender, EventArgs e)  
  40.         {  
  41.   
  42.               
  43.             DataGridViewImageColumn dgvimgcol = new DataGridViewImageColumn();  
  44.             dgvimgcol.HeaderText = "Uploaded Image";  
  45.             dgvimgcol.ImageLayout = DataGridViewImageCellLayout.Stretch;  
  46.             
  47.             dataGridView1.Columns.Add(dgvimgcol);  
  48.          
  49.             dataGridView1.RowTemplate.Height = 250;  
  50.            
  51.             dataGridView1.AllowUserToAddRows = false;  
  52.         }  
  53.     }  
  54. }  
Output chamber

Output

upload image

Hope you liked it. Thank you for reading. Have a good day.

Up Next
    Ebook Download
    View all
    Learn
    View all