单击单元格时选中 Datagridview 复选框

Datagridview checkbox checked when clicking the cell

我用 CurrentCellDirtyStateChanged 处理我的复选框点击事件。我想要做的是在我单击也包含复选框的 单元格 时处理相同的事件,即当我单击该单元格时,选中该复选框并调用 DirtyStateChanged。使用下面的代码没有多大帮助,它甚至没有调用 CurrentCellDirtyStateChanged。我 运行 没主意了。

private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if(dataGridView.Columns[e.ColumnIndex].ReadOnly != true)
    {       
          //option 1
          (dataGridView.CurrentRow.Cells[e.ColumnIndex] as DataGridViewCheckBoxCell).Value = true;
          //option 2
          DataGridViewCheckBoxCell cbc = (dataGridView.CurrentRow.Cells[e.ColumnIndex] as DataGridViewCheckBoxCell);
          cbc.Value = true;
          //option 3
          dataGridView.CurrentCell.Value = true;
    }

}

这应该可以满足您的要求:

private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if(dataGridView.Columns[e.ColumnIndex].ReadOnly != true)
    {       
        dataGridView.CurrentCell.Value = true;
        dataGridView.NotifyCurrentCellDirty(true);
    }
}

正如 Bioukh 指出的那样,您必须调用 NotifyCurrentCellDirty(true) 来触发您的事件处理程序。但是,添加该行将不再更新您的选中状态。要在单击 时完成检查状态更改,我们将添加对RefreshEdit 的调用。这将用于在单击单元格时切换单元格选中状态,但它也会使实际复选框的第一次单击有点错误。所以我们添加 CellContentClick 事件处理程序,如下所示,您应该可以开始了。


private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
  DataGridViewCheckBoxCell cell = this.dataGridView1.CurrentCell as DataGridViewCheckBoxCell;

  if (cell != null && !cell.ReadOnly)
  {
    cell.Value = cell.Value == null || !((bool)cell.Value);
    this.dataGridView1.RefreshEdit();
    this.dataGridView1.NotifyCurrentCellDirty(true);
  }
}

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
  this.dataGridView1.RefreshEdit();
}
private void dataGridView3_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex == dataGridView3.Columns["Select"].Index)//checking for select click
        {
            dataGridView3.CurrentCell.Value = dataGridView3.CurrentCell.FormattedValue.ToString() == "True" ? false : true;
            dataGridView3.RefreshEdit();
        }
    }

这些更改对我有用!