假设DataGridViewCheckBoxColumn
您添加的任何内容都遵循以下模式:
DataGridViewCheckBoxColumn cbc = new DataGridViewCheckBoxColumn();
cbc.ThreeState = true;
this.dataGridView1.Columns.Add(cbc);
然后您需要做的就是将以下事件处理程序添加到您DataGridView
的单击并双击复选框:
this.dataGridView1.CellContentClick += ThreeState_CheckBoxClick;
this.dataGridView1.CellContentDoubleClick += ThreeState_CheckBoxClick;
private void ThreeState_CheckBoxClick(object sender, DataGridViewCellEventArgs e)
{
DataGridViewCheckBoxColumn col = this.dataGridView1.Columns[e.ColumnIndex] as DataGridViewCheckBoxColumn;
if (col != null && col.ThreeState)
{
CheckState state = (CheckState)this.dataGridView1[e.ColumnIndex, e.RowIndex].EditedFormattedValue;
if (state == CheckState.Unchecked)
{
this.dataGridView1[e.ColumnIndex, e.RowIndex].Value = CheckState.Checked;
this.dataGridView1.RefreshEdit();
this.dataGridView1.NotifyCurrentCellDirty(true);
}
}
}
本质上,默认的切换顺序是:Checked => Indeterminate => Unchecked => Checked
. 因此,当单击事件触发一个Uncheck
值时,您将其设置为Checked
并强制网格使用新值刷新。