2

我正在使用 DataGridView 并设置了一些 DataGridViewCheckBoxColumns,其中两个将 ThreeState 属性设置为 True。

对于我网格中的某些行,我只希望复选框被选中或不确定。Unchecked 永远不应该对用户可用。但是如果用户反复点击复选框,它会从选中变为不确定再到未选中。我只想让它检查,不确定,检查,不确定等。

有没有办法在单击时停止选中/取消选中复选框(类似于标准 Windows 窗体 Checkbox 控件上的 AutoCheck 属性),或者是否有一个事件可以用来取消 DataGridViewCheckBoxCell 的选中更改?

我试图以编程方式强制选中的单元格从未选中变为选中或不确定,但 UI 从未反映这一点。

4

1 回答 1

2

假设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并强制网格使用新值刷新。

于 2015-09-25T19:09:32.110 回答