DataGridView with a checkbox with default value checked

38,321

Solution 1

I think there is no way of setting the checked value on column declaration. You will have to iterate through the rows checking it after datasource is set (for example in DataBindingComplete event):

for (int i = 0; i < dataGridView1.Rows.Count -1; i++)
{
dataGridView1.Rows[i].Cells[0].Value = true;
}

With your column name:

for (int i = 0; i < dataGridView1.Rows.Count -1; i++)
{
   dataGridView1.Rows[i].Cells["Export"].Value = true;
}

Solution 2

Try to do it like this:

foreach (DataGridViewRow row in dgv.Rows)     
{
    row.Cells[CheckBoxColumn.Name].Value = true;     
} 

Solution 3

Make sure your DataGridView is shown when you set the value of your DataGridViewCheckBoxCells: I had mine in the second tab of a TabControl and the cells were always unchecked after initialization. To solve this, I had to move cell initialization to TabControl's SelectedIndexChanged event.

private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (this.tabControl1.SelectedIndex == 1)
    {
        foreach (DataGridViewRow row in this.myGridView.Rows)
        {
            ((DataGridViewCheckBoxCell)row.Cells[0]).Value = true;
        }
    }
}
Share:
38,321
meirrav
Author by

meirrav

junior software engineer

Updated on November 16, 2021

Comments

  • meirrav
    meirrav over 2 years

    I have a dataGridView in a Winform, I added to the datagrid a column with a checkbox using a code I saw here :

        DataGridViewCheckBoxColumn column = new DataGridViewCheckBoxColumn();
        {
            column.HeaderText = "Export";
            column.Name = "Export";
            column.AutoSizeMode =
                DataGridViewAutoSizeColumnMode.DisplayedCells;
            column.FlatStyle = FlatStyle.Standard;
            column.CellTemplate = new DataGridViewCheckBoxCell(false);
            column.CellTemplate.Style.BackColor = Color.White;
        }
    
        gStudyTable.Columns.Insert(0, column);  
    

    this works but I want the checkBox to be checked as a default saw I added :

        foreach (DataGridViewRow row in gStudyTable.Rows)
        {                
            row.Cells[0].Value = true;
        }
    

    but the checkbox col is still unchecked. I'm using a collection as my data source and I change the value of the col after I added the data source.