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

时间:2015-04-01 19:13:29

标签: 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;
    }

}

3 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:1)

这应该做你想要的:

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

答案 2 :(得分:0)

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

这些改变对我有用了!