Click here to Skip to main content
15,887,350 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want all checkboxes to appear as “false” initially.
CBColumn.DataPropertyName = "id";
is causing all checkboxes to be checked. But when I remove the line
CBColumn.DataPropertyName = "id";
then I can’t send the “id” value. I want to send id value.

What I have tried:

My codes are these. How can I succeed this?

C#
DataGridViewCheckBoxColumn CBColumn = new DataGridViewCheckBoxColumn();
           CBColumn.Width = 30;
           CBColumn.FalseValue = "0";
           CBColumn.TrueValue = "1";
           CBColumn.DataPropertyName = "id";
           CBColumn.ReadOnly = false;
           dataGridView1.Columns.Insert(0, CBColumn);
Posted
Updated 9-Jun-23 1:27am
v2

1 solution

When you set the DataPropertyName property of the DataGridViewCheckBoxColumn to 'id', it automatically binds the checkbox column to the property in the data source. It seems that the values in the "id" property is shown as boolean values, where a non-empty string is considered 'true' and an empty string is considered 'false'.

To set all your checkboxes to 'false' initially without affecting the 'id' value, you can store the original 'DataPropertyName' value in a temporary variable before setting it to null. This disables the data binding temporarily. Then, after inserting the column into the dataGridView1, loop through each row and set the value of the checkbox cell to false/'0'.

You can then restore the 'DataPropertyName' back to its original value, which allows you to get the correct 'id' values' -
DataGridViewCheckBoxColumn CBColumn = new DataGridViewCheckBoxColumn();
CBColumn.Width = 30;
CBColumn.FalseValue = "0";
CBColumn.TrueValue = "1";
CBColumn.ReadOnly = false;

// Temporarily remove the DataPropertyName
string dataPropertyName = CBColumn.DataPropertyName;
CBColumn.DataPropertyName = null;

dataGridView1.Columns.Insert(0, CBColumn);

// Set all checkboxes to "false" initially
foreach (DataGridViewRow row in dataGridView1.Rows)
{
    DataGridViewCheckBoxCell checkBoxCell = (DataGridViewCheckBoxCell)row.Cells[0];
    checkBoxCell.Value = CBColumn.FalseValue;
}

// Restore the DataPropertyName
CBColumn.DataPropertyName = dataPropertyName;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900