Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# DataGridViewCheckBoxColumn Hide/Gray-Out

I have a DataGridView with several columns and several rows of data. One of the columns is a DataGridViewCheckBoxColumn and (based on the other data in the row) I would like the option to "hide" the checkbox in some rows. I know how to make it read only but I would prefer it to not show up at all or at least display differently (grayed out) than the other checkboxes. Is this possible?

like image 271
john Avatar asked Dec 17 '22 08:12

john


1 Answers

Some workaround: make it read-only and change back color to gray. For one specific cell:

dataGridView1.Rows[2].Cells[1].Style.BackColor =  Color.LightGray;
dataGridView1.Rows[2].Cells[1].ReadOnly = true;

Or, better but more "complicated" solution:
suppose you have 2 columns: first with number, second with checkbox, that should not be visible when number > 2. You can handle CellPainting event, paint only borders (and eg. background) and break painting of rest. Add event CellPainting for DataGridView (optionally test for DBNull value to avoid exception when adding new data in empty row):

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    //check only for cells of second column, except header
    if ((e.ColumnIndex == 1) && (e.RowIndex > -1))
    {
        //make sure not a null value
        if (dataGridView1.Rows[e.RowIndex].Cells[0].Value != DBNull.Value)
        {
            //put condition when not to paint checkbox
            if (Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value) > 2)
            {
                e.Paint(e.ClipBounds, DataGridViewPaintParts.Border | DataGridViewPaintParts.Background);  //put what to draw
                e.Handled = true;   //skip rest of painting event
            }
        }
    }
}

It should work, however if you change value manually in first column, where you check condition, you must refresh the second cell, so add another event like CellValueChanged:

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 0)
    {
        dataGridView1.InvalidateCell(1, e.RowIndex);
    }
}
like image 102
mj82 Avatar answered Jan 03 '23 13:01

mj82