0

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.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
ihisham
  • 248
  • 1
  • 10

1 Answers1

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 enter image description here and UnChecked enter image description here images to Resources.

Then you will see such result:

enter image description here

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