c# - 单击单元格时选中 Datagridview 复选框

标签 c# winforms checkbox datagridview checked

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

}

最佳答案

正如 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();
}

关于c# - 单击单元格时选中 Datagridview 复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29398941/

相关文章:

html - 对齐复选框

c# - 在 Windows 应用商店应用程序上更改 BLE MTU

c# - 如何取消选中 DataGridView 中的复选框

c# - Entity Framework 未获取复杂类型的列

jquery - AddClass和RemoveClass在浏览器上的行为不同

javascript - 为什么我能够在live站点上 "check" "disabled"checkbox,数据成功上传到服务器

c# - 如何通过c#访问localhost连接MySQL数据库?

c# - 尽管使用 Filter 选项,SaveFileDialog 不显示任何可能的扩展名

.net - 用 Visual Basic 编写的 Windows 窗体应用程序是否也需要 VB 运行时?

c# - ProgressBar 没有值(value),只是加载