单击单元格时,将检查Datagridview复选框

Jnr*_*Jnr 2 c# checkbox datagridview checked winforms

我使用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;
    }

}
Run Code Online (Sandbox Code Playgroud)

OhB*_*ise 8

正如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);
  }
}
Run Code Online (Sandbox Code Playgroud)
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
  this.dataGridView1.RefreshEdit();
}
Run Code Online (Sandbox Code Playgroud)

  • 这是一个很好的问题,我没有提到datagridview是数据绑定的.所以值是DBNull.我使用dataGridView.CurrentCell.Value = true而不是使用强制转换为bool.谢谢您的帮助! (2认同)