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.
Asked
Active
Viewed 75 times
0

Reza Aghaei
- 120,393
- 18
- 203
- 398

ihisham
- 248
- 1
- 10
-
So what's your question? What have you tried? – Marshall Tigerus Oct 10 '17 at 15:10
-
so far i'm stuck in the paint method. don't know what to do in it – ihisham Oct 10 '17 at 15:14
-
No need to inherit anything. Just use the grid's CellPainting event. – LarsTech Oct 10 '17 at 15:16
-
@ihisham Did you try finding out how to draw an image in winforms? – 15ee8f99-57ff-4f92-890c-b56153 Oct 10 '17 at 15:16
1 Answers
1
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;
}
}

Reza Aghaei
- 120,393
- 18
- 203
- 398
-
quick question i moved the code to a stand alone DataGridViewColumn so i can use it freely. it's working but i don't get the visual update when i'm in edit mode, the update takes effect only when i quit it. any idea why ? – ihisham Oct 12 '17 at 10:15
-
Are you sure you derived from `DataGridViewCheckBoxColumn`? Hmmm, maybe it would be better to post a new question containing the code of the custom column which you created. – Reza Aghaei Oct 12 '17 at 10:31
-
here i post the problem with the code used https://stackoverflow.com/questions/46709110/custom-datagridviewcheckboxcell-visual-update-doesnt-work-in-edit-mode – ihisham Oct 12 '17 at 12:02