Hi,
I think it’s better to use DataGridView.CurrentCellDirtyStataChanged event to catch the value changed if you want to get the changed value when users click the cell. Please refer to the remarks part of DataGridViewCheckBoxCell Class.
void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dataGridView1.CurrentCell is DataGridViewCheckBoxCell && dataGridView1.IsCurrentCellDirty)
// or dataGridView1.CurrentCell.ColumnIndex == 0
{
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
int i = 0;
foreach (DataGridViewRow r in dataGridView1.Rows)
{
if (r.Cells["Test"].Value != null)
{
if (((bool)r.Cells["Test"].Value) == true)
Console.WriteLine(i++.ToString());
}
}
if (i == dataGridView1.Rows.Count - 1)
{
chbox.Checked = true;
}
else
{
chbox.Checked = false;
}
}
}
You need also consider when users resize the column wide. The checkbox need to be resized, too. You can create a custom check box head cell.
More information:
Bruce Zhou has written a full demo for this.
http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/0572255e-5bf1-4684-947e-526de587c1fa
Column Header CheckBox in DataGridView (Winfoms)
http://www.codeproject.com/KB/grid/DataGridView_winforms.aspx
CheckBox Header Column For DataGridView
http://www.codeproject.com/KB/grid/CheckBoxHeaderCell.aspx
DataGridView.CurrentCellDirtyStateChanged Event
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.currentcelldirtystatechanged.aspx
Best regards,
Ling Wang
Please remember to click “Mark as Answer�on the post that helps you, and to click “Unmark as Answer�if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.