我使用 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/