Check/Uncheck a checkbox on datagridview

Looking at this MSDN Forum Posting it suggests comparing the Cell’s value with Cell.TrueValue.

So going by its example your code should looks something like this:(this is completely untested)

Edit: it seems that the Default for Cell.TrueValue for an Unbound DataGridViewCheckBox is null you will need to set it in the Column definition.

private void chkItems_CheckedChanged(object sender, EventArgs e)
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[1];
        if (chk.Value  == chk.TrueValue)
        {
            chk.Value = chk.FalseValue;
        }
        else
        {
            chk.Value = chk.TrueValue;
        }
    }
}

This code is working note setting the TrueValue and FalseValue in the Constructor plus also checking for null:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        DataGridViewCheckBoxColumn CheckboxColumn = new DataGridViewCheckBoxColumn();
        CheckboxColumn.TrueValue = true;
        CheckboxColumn.FalseValue = false;
        CheckboxColumn.Width = 100;
        dataGridView1.Columns.Add(CheckboxColumn);
        dataGridView1.Rows.Add(4);
    }

    private void chkItems_CheckedChanged(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
            if (chk.Value == chk.FalseValue || chk.Value == null)
            {
                chk.Value = chk.TrueValue;
            }
            else
            {
                chk.Value = chk.FalseValue;
            }

        }
        dataGridView1.EndEdit();
    }
}

Leave a Comment