C
C#4mo ago
Hazzza

Trying to detect when a checkbox is ticked/unticked in a datagridview checkbox column (WinForms)

Check Box Column Creation Code:
C#
DataGridViewCheckBoxColumn RestrictIngredientColumn = new DataGridViewCheckBoxColumn();
RestrictIngredientColumn.ValueType = typeof(bool);
RestrictIngredientColumn.Width = 50;
RestrictIngredientColumn.Name = "Restrict";
RestrictIngredientColumn.HeaderText = "Restrict";
dgvOptimiseIngredients.Columns.Add(RestrictIngredientColumn);
C#
DataGridViewCheckBoxColumn RestrictIngredientColumn = new DataGridViewCheckBoxColumn();
RestrictIngredientColumn.ValueType = typeof(bool);
RestrictIngredientColumn.Width = 50;
RestrictIngredientColumn.Name = "Restrict";
RestrictIngredientColumn.HeaderText = "Restrict";
dgvOptimiseIngredients.Columns.Add(RestrictIngredientColumn);
Checkbox Click Detection Code: (Column[1] is the column of checkboxes)
C#
private void dgvOptimiseIngredients_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 1 && e.RowIndex != -1)
{
DataGridViewCell cell = dgvOptimiseIngredients[e.ColumnIndex, e.RowIndex];

MessageBox.Show((Convert.ToBoolean(cell.Value) == true).ToString());
}
}
C#
private void dgvOptimiseIngredients_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 1 && e.RowIndex != -1)
{
DataGridViewCell cell = dgvOptimiseIngredients[e.ColumnIndex, e.RowIndex];

MessageBox.Show((Convert.ToBoolean(cell.Value) == true).ToString());
}
}
Showcase of output: https://gyazo.com/101659e8af97d91876baa8a6cf4d1834 Seems to return true/false very randomly anyone have any idea why this happens. Thanks
3 Replies
Nasdack
Nasdack4mo ago
It is not returning randomly. It is the opposite of what seems to be right This happens when your click handler returns the value of the CheckBoxCell before it actually has time to commit its value changes CurrentCellDirtyStateChanged is the event to handle this commit stuff
Hazzza
HazzzaOP4mo ago
Thank you I’ll have a go with this later I’ll let you know how it goes That worked thank you

Did you find this page helpful?