I want to have DataGridViewButtonColumn
acting as DataGridViewCheckBoxColumn
. Meaning having some image inside the button as a true
and another image as a false
and bound to a property by DataMember
.
I think a class inheriting from DataGridViewCheckBoxColumn
and override
the paint
method "should" work.
Just use the DataGridViewCheckBoxColumn
but handle CellPaint
event of DataGridView
and draw an image for checked state and another for unchecked state.
Example
Create a Form
named Form1
and then drop a DataGridView
control on form and replace content of Form1.cs
with following code. Also make sure you added Checked
and
UnChecked
images to
Resources
.
Then you will see such result:
public Form1()
{
InitializeComponent();
this.Load += Form1_Load;
this.dataGridView1.CellPainting += dataGridView1_CellPainting;
}
private void Form1_Load(object sender, EventArgs e)
{
var dt = new DataTable();
dt.Columns.Add("Column1", typeof(bool));
dt.Rows.Add(false);
dt.Rows.Add(true);
this.dataGridView1.DataSource = dt;
}
void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex == 0 && e.RowIndex >= 0)
{
var value = (bool?)e.FormattedValue;
e.Paint(e.CellBounds, DataGridViewPaintParts.All &
~DataGridViewPaintParts.ContentForeground);
var img = value.HasValue && value.Value ?
Properties.Resources.Checked : Properties.Resources.UnChecked;
var size = img.Size;
var location = new Point((e.CellBounds.Width - size.Width) / 2,
(e.CellBounds.Height - size.Height) / 2);
location.Offset(e.CellBounds.Location);
e.Graphics.DrawImage(img, location);
e.Handled = true;
}
}