Friday 16 November 2012

How to add the Image Column and Image to DataGridview control

As we know DataGridView is more important and more use full in realtime windows applications.And this control and classes are Designed to be more flexible and also Extensible           
And We can add an Image control in a column of DataGridView.Setting the column Image property results in that image being displayed by default for all the cells in that column.
The following C# program shows how to add a Image in column of a DataGridView control.

 figur1 shows form and datagridview:

code snippet:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace dgvImage
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnDgv_Click(object sender, EventArgs e)
       {
            dataGridView1.ColumnCount = 3;
            dataGridView1.Columns[0].Name = "Product ID";
            dataGridView1.Columns[1].Name = "Product Name";
            dataGridView1.Columns[2].Name = "Product Price";

            string[] row = new string[] { "1", "Product 1", "1000" };
            dataGridView1.Rows.Add(row);
            row = new string[] { "2", "Product 2", "2000" };
            dataGridView1.Rows.Add(row);
            row = new string[] { "3", "Product 3", "3000" };
            dataGridView1.Rows.Add(row);
            row = new string[] { "4", "Product 4", "4000" };
            dataGridView1.Rows.Add(row);

            DataGridViewImageColumn img = new DataGridViewImageColumn();
            Image image = Image.FromFile("image Path");//Here we have to give the image path
            img.Image = image;
            dataGridView1.Columns.Add(img);
            img.HeaderText = "Image";
            img.Name = "img";

        }
    }
}
figur2 shows Result of the form:

I hope this code will help you