繁体   English   中英

单击单元格时选中 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;
    }

}

正如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 dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if(dataGridView.Columns[e.ColumnIndex].ReadOnly != true)
    {       
        dataGridView.CurrentCell.Value = true;
        dataGridView.NotifyCurrentCellDirty(true);
    }
}
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();
        }
    }

这些变化对我有用!

在 HelperClass 中使用 static function 的HelperClass解决方案的更通用方法

public static void DataGrid_CheckBoxCellClick(object sender, DataGridViewCellEventArgs e)
{
    DataGridView dataGrid = sender as DataGridView;
    DataGridViewCheckBoxCell cell = dataGrid?.CurrentCell as DataGridViewCheckBoxCell;

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

在你的代码后面

dataGridView1.CellClick += HelperClass.DataGrid_CheckBoxCellClick;

不需要下面的代码:-)

if(dataGridView.Columns[e.ColumnIndex].ReadOnly != true)

你可以写得更简单:

if(!dataGridView.Columns[e.ColumnIndex].ReadOnly)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM