Draw an Icon in a DataGridViewButtonCell
Here is a simple example on how to draw in a DataGridViewButtonCell. In this example an icon is displayed when button is pushed and the icon is made invisible when its pushed again. I am storing the if the button has been pressed in the cell's tag. I use the cellPainting event to draw the icon when needed.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace CSButtonColumn
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
String strConn = "Server = .\\SqlExpress;Database = Pubs;Integrated Security = SSPI;";
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection(strConn);
SqlDataAdapter da = new SqlDataAdapter("Select * from titles", conn);
da.Fill(dt);
dataGridView1.DataSource = dt;
DataGridViewButtonColumn bc = new DataGridViewButtonColumn();
bc.Tag = false;
dataGridView1.Columns.Insert(0, bc);
}
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == 0)
{
e.Value = "Repair";
e.FormattingApplied = true;
}
}
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex == 0 && e.RowIndex >= 0)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All);
DataGridViewButtonCell bc = dataGridView1[0, e.RowIndex] as DataGridViewButtonCell;
bool x;
if (bc.Tag == null)
{
x = false;
}
else
{
x = (bool)bc.Tag;
}
if (x)
{
Icon ico = new Icon("repair.ico");
e.Graphics.DrawIcon(ico, e.CellBounds.Left+3, e.CellBounds.Top+3 );
}
e.Handled = true;
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0 && e.RowIndex >= 0)
{
DataGridViewButtonCell bc = dataGridView1[e.ColumnIndex, e.RowIndex] as DataGridViewButtonCell;
if (bc.Tag == null)
{
bc.Tag = true;
}
else
{
bc.Tag = !(bool)bc.Tag;
}
}
}
}
}