单击单元格时选中了Datagridview复选框 [英] Datagridview checkbox checked when clicking the cell

查看:506
本文介绍了单击单元格时选中了Datagridview复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 CurrentCellDirtyStateChanged 处理我的复选框点击事件。我想要做的是处理相同的事件,当我点击包含复选框的单元格,即当我单击单元格,选中复选框,并调用DirtyStateChanged。使用下面的代码没有什么帮助,它甚至不调用 CurrentCellDirtyStateChanged 。

I handle my checkbox click event with the CurrentCellDirtyStateChanged. What I want to be able to do is handle the same event when I click the cell that contains the checkbox too, i.e. when I click the cell, check the checkbox and call the DirtyStateChanged. Using the following code does not help much, it does not even call the CurrentCellDirtyStateChanged. I've run out of ideas.

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;
    }

}


推荐答案

As Bioukh指出,您必须调用 NotifyCurrentCellDirty(true)才能触发您的事件处理程序。但是,添加该行将不再更新您的已选中状态。要在点击完成您的选中状态更改,我们将添加对 RefreshEdit 的调用。这将工作,以切换您的单元格被选中的状态,当单元格被点击,但它也将使第一次点击实际的复选框有点儿车。因此,我们添加 CellContentClick 事件处理程序,如下所示,您应该很好。

As Bioukh points out, you must call NotifyCurrentCellDirty(true) to trigger your event handler. However, adding that line will no longer update your checked state. To finalize your checked state change on click we'll add a call to RefreshEdit. This will work to toggle your cell checked state when the cell is clicked, but it will also make the first click of the actual checkbox a bit buggy. So we add the CellContentClick event handler as shown below and you should be good to go.

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

这篇关于单击单元格时选中了Datagridview复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆