C# – How to hide a particular checkbox cell in datagridview

cdatagridviewwinforms

I have a datagridview that has some textboxtype columns and one checkboxtype column. CheckBoxColumn bind with a bool type property.

I want that if checkbox is checked it see in the grid else not as shown in figure.

enter image description here

I have added some code in databinding complete but it is giving compile time error "Property or indexer 'System.Windows.Forms.DataGridViewCell.Visible' cannot be assigned to -- it is read only"

private void dgvleftEdit_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{   
    var reportLogoList = cWShowInvoicePaymentDetailsBindingSource.List as IList<CWShowInvoicePaymentDetails>;

    foreach (DataGridViewRow row in dgvleftEdit.Rows)
    {
        var objReport = row.DataBoundItem as CWShowInvoicePaymentDetails;
        var findItem = from f in reportLogoList
                       //where f.fReportID == objReport.fKey
                       select f;
        if (objReport.IsImage == false)
        {
            this.dgvleftEdit.Rows[row.Index].Cells[7].Visible = false;
        }
        else
        {
            this.dgvleftEdit.Rows[row.Index].Cells[7].Visible = true;
        }
    } 
}

Is it possible to hide a particular cell in datagridview?

Best Answer

I think this is what you want, if not leave some comment for why:

//CellPainting event handler for your dataGridView1
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) {
   if (e.ColumnIndex > -1 && e.RowIndex > -1 && dataGridView1.Columns[e.ColumnIndex] is DataGridViewCheckBoxColumn){
     if (e.Value == null || !(bool)e.Value) {
         e.PaintBackground(e.CellBounds, false);
         e.Handled = true;
     }
   }
}
//CellBeginEdit event handler for your dataGridView1
private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e){
   if (dataGridView1.Columns[e.ColumnIndex] is DataGridViewCheckBoxColumn){
            object cellValue = dataGridView1[e.ColumnIndex, e.RowIndex].Value;
            e.Cancel = cellValue == null || !(bool)cellValue;
   }
}