Nusser
Nusser

Reputation: 11

How to hide CheckBox in DataGridView if value of cell is null

I have Winform with DataGridView filled from table which contains bit columns. I need to hide the CheckBox if the values is null, and keep it visible if the value is true or false.

How do I hide CheckBox in DataGridView if value of cell is null?

Upvotes: 0

Views: 437

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125197

Handle CellPainting event and don't draw the check box in case the value of cell is null or DBNnull.Value:

private void DataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if (e.RowIndex >= 0 && e.ColumnIndex == 1 && 
       (e.Value == DBNull.Value || e.Value == null))
    {
        e.Paint(e.ClipBounds, DataGridViewPaintParts.All &
            ~DataGridViewPaintParts.ContentForeground);
        e.Handled = true;
    }
}

Note:

  • e.RowIndex >= 0 Makes sure we are rendering the data cells, not the header cells.
  • e.ColumnIndex == 1 Makes sure we are applying the logic for the column at index 1. If you want the logic for another column, use فhat column's index.
  • e.Paint(...); Is paining all parts of the cell, except the cell content foreground which is the check box.
  • e.Handled = true; Sets the painting as handled, so the default paint logic will not run.
  • It doesn't make the cell read-only. It just skips rendering the checkbox.
  • Don't forget to add the event handler to the event.

Upvotes: 1

Related Questions