假设任何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
,并强制网格用新值刷新。
非常感谢你,这个伎俩。我在正确的道路上,但没有最后两行来刷新和通知。谢谢 :) – AndyG