meirrav meirrav - 2 months ago 36
C# Question

DataGridView with a checkbox with default value checked

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.

Answer

I think there is no way of setting the checked value on column declaration. You will have to irerate 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;
}