Display Image instead of CheckBox in DataGridView

| July 31, 2010 | 6 Comments

Well! I am not so much expert about the Window Controls. But sometimes we get stuck by problem which seems to easy. I tried lot on internet but I didn’t get solution as I wanted. After spending three to four hours ( yes it’s true) I found a solution which is working fine.

So what’s the problem is that you need to display image instead of Checkbox in DataGridView. That is instead of True/False we will show images. Read out rest of section to know how to do that silly thing.

DataGrid showing Checkbox

DataGrid showing Checkbox

Checkbox replaced with Images

Checkbox replaced with Images

Requirements:

You would need to follow some of the requirements for running code provided.

  • The application is been built on Visual Studio 2008 so you would need it.
  • Set the ConnectionString according to your system.
  • You should have database with some bit type values for well testing of the application
  • You would need to do some little modifications in code more as instructed within code.

About Project:

I have used DataGridView control with Name gridViewData and a single Buttonto get data from database. Below are the approaches I tried for doing this project in other way; but I not succeeded:

  1. First I tried about creating new DataTable based on the DataTable created with the help of data I got from database. And when I done it completely I was seeing value with name System.Drawing.Bitmap instead of image. So I canceled the idea.
  2. Then I tried to convert the type of DataGridViewCheckBoxColumn to DataGridViewImageColumn. But again program was showing error, “Cannot cast CheckBoxColumn to Bitmap type. So I leaved it.
  3. While searching MSDN 2008 I found about DataGridView.CellFormatting event and tried lot on it to do but here it was not sorting the image column properly. And hence rejected this too.
  4. After that I just simply added DataGridViewImageColumn  into DataGridView with name property and added rows in column. But after this I face problem of sorting as while sorting all images value get replaced with crossed image.
  5. Now for Sorting I again searched lovely MSDN and I came to know about Sort method and SortCompare event. While reading documentation I learn that if DataGridView is bound  with some DataSource the SortCompare event not occur and Sort will not work. Finally I tried ColumnHeaderMouseClick event of DataGridView because for Sorting we use to click on ColumnHeader.

Code Snippet:

I think I have bore you too much. Now working time. Below is the code snippet of the file Form1.cs. You can download full application from above link in begining.

using System;
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;
using System.Data.SqlClient;
using System.Collections;

namespace ee_DataGrid
{
    public partial class Form1 : Form
    {
        private Bitmap trueImg, falseImg;
        public Form1()
        {
            InitializeComponent();

            trueImg = (Bitmap)Image.FromFile(Application.StartupPath + @"\Images\true.png");
            falseImg = (Bitmap)Image.FromFile(Application.StartupPath + @"\Images\false.png");

            // Sorting image with this event
            gridViewData.ColumnHeaderMouseClick += new DataGridViewCellMouseEventHandler(gridViewData_ColumnHeaderMouseClick);
        }

        private void btnGetData_Click(object sender, EventArgs e)
        {
            try
            {
                #region Filling DataGridView named gridViewData values
                // Change connectionString
                String connectionString = "Initial Catalog=TestDB;Data Source=localhost; Uid=sa; pwd=god";
                SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT * FROM UID", connectionString);
                SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

                DataTable table = new DataTable();
                dataAdapter.Fill(table);
                gridViewData.DataSource = table;
                gridViewData.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);

                #endregion

                #region Showing image instead of checkbox

                // Hiding checkbox values
               //  Is Indian is the name of the column in which Checkbox values are displayed
               // So change it according to your database
                gridViewData.Columns["Is Indian"].Visible = false;

                DataGridViewImageColumn imageCol = new DataGridViewImageColumn();
                imageCol.Name = "Is Indian";
                imageCol.SortMode = DataGridViewColumnSortMode.Automatic;
                gridViewData.Columns.Add(imageCol);

                foreach (DataGridViewRow row in gridViewData.Rows)
                {
                    if (row.Cells["Is Indian"].Value != null)
                    {
                        if (Convert.ToBoolean(row.Cells["Is Indian"].Value))
                        {
                            // Cells[3] is the position of the cell in the row
                            row.Cells[3].Value = trueImg;
                        }
                        else
                        {
                            row.Cells[3].Value = falseImg;
                        }
                    }
                }
                #endregion
            }
            catch (Exception exc)
            {
                MessageBox.Show("Contact Developer\nTechnical Report: " + exc.ToString());
            }
        }

        void gridViewData_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            foreach (DataGridViewRow row in gridViewData.Rows)
            {
                if (row.Cells["Is Indian"].Value != null)
                {
                    if (Convert.ToBoolean(row.Cells["Is Indian"].Value))
                    {
                        // Cells[3] is the position of the cell in the row
                       //  It is the position and last where you want to display images in column
                        row.Cells[3].Value = trueImg;
                    }
                    else
                    {
                        row.Cells[3].Value = falseImg;
                    }
                }
            }
        }
    }
}

So the silly thing as mentioned earlier is working very smoothly. If you like it or hate it do not forget to leave your comments.

And here is the link to the page where you can get more solution for Show image instead of Checkbox in DataGridView

Download Source Code

Tags: ,

Category: .NET, C#

Comments (6)

Trackback URL | Comments RSS Feed

  1. jai says:

    hello sir can u tell me how to use loop between two datetimepicker ………………..slect from date ———-to date show all date in data grid view

  2. Hello mr. Saini, I hope you can help me with the following.

    I’ve been trying to get the code for the checkbox to image column to work (vb2010), but I keep getting an error message, just like millitheKidd.

    I am using ms access with a numeric (bit) column.

    Can you please help. Here is the code I use:

    Dim imageCol As New DataGridViewImageColumn()
    imageCol.Name = “Trumpet”
    ‘imageCol.SortMode = DataGridViewColumnSortMode.Automatic
    DataGridViewX1.Columns.Add(imageCol)
    For Each row As DataGridViewRow In DataGridViewX1.Rows
    If row.Cells(“Trumpet”).Value IsNot Nothing Then
    If (Convert.ToBoolean(row.Cells(“Trumpet”).Value)) Then
    ‘ Cells[3] is the position of the cell in the row
    row.Cells(3).Value = trueImg
    Else
    row.Cells(3).Value = falseImg
    End If
    End If
    Next

    The following code I have in the form2_load event:

    trueImg = DirectCast(Image.FromFile(Application.StartupPath & “\Image\trumpet.png”), Bitmap)
    falseImg = DirectCast(Image.FromFile(Application.StartupPath & “\Image\no-trumpet.png”), Bitmap)

  3. Hello mr. Saini, I hope you can help me with the following.

    I’ve been trying to get the code for the checkbox to image column to work (vb2010), but I keep getting an error message, just like millitheKidd.

    I am using ms access with a numeric (bit) column.

    Can you please help. Here is the code I use:

    Dim imageCol As New DataGridViewImageColumn()
    imageCol.Name = “Trumpet”
    ‘imageCol.SortMode = DataGridViewColumnSortMode.Automatic
    DataGridViewX1.Columns.Add(imageCol)
    For Each row As DataGridViewRow In DataGridViewX1.Rows
    If row.Cells(“Trumpet”).Value IsNot Nothing Then
    If (Convert.ToBoolean(row.Cells(“Trumpet”).Value)) Then
    ‘ Cells[3] is the position of the cell in the row
    row.Cells(3).Value = trueImg
    Else
    row.Cells(3).Value = falseImg
    End If
    End If
    Next

    The following code I have in the form2_load event:

    trueImg = DirectCast(Image.FromFile(Application.StartupPath & “\Image\trumpet.png”), Bitmap)
    falseImg = DirectCast(Image.FromFile(Application.StartupPath & “\Image\no-trumpet.png”), Bitmap)

  4. millitheKidd says:

    Hello Mr. Saini, thanks for replying,
    It seems to be throwing the error at the line below:

    <br />If Convert.ToBoolean(row.Cells("SignAgreement").Value) Then<br />

    Please note, I have converted your example to VB.Net. Once again, thank you, really good code example.

  5. V.S. Saini says:

    @ millitheKidd ,

    Please let me know at which line you are facing above problem?

    And share your code along with.

  6. millitheKidd says:

    Hello Mr. Saini,
    when I try to run it, says:
    System.Argument.Exception: Unable to cast object of type ‘System.Drawing.Bitmap’ to type ‘System.IConvertible’. Couldn’t store in SignAgreement column. Expected type is Boolean.

    SignAgreement is the name of my column and it is a Bit DataType. It is a SQL Server 2000 database.
    Thank you.

Leave a Reply

Sex Chat Live Jasmin WP-Clear 3.0 Theme
%d bloggers like this: