DataGridView中的复选框未触发CellValueChanged事件

use*_*034 7 .net c# checkbox datagridview winforms

我正在使用此代码:

// Cell value change event.
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if ((bool)dataGridView1.CurrentCell.Value == true) MessageBox.Show("true");
    if ((bool)dataGridView1.CurrentCell.Value == false) MessageBox.Show("false");

    MessageBox.Show(dataGridView1.CurrentCell.Value.ToString());
}
Run Code Online (Sandbox Code Playgroud)

它适用于所有列,除了一列带复选框(DataGridViewCheckBoxColumn)

我需要知道复选框列中的值(true或false).

我需要做什么呢?

Der*_*k W 17

使用DataGridViewCheckBoxColumn有时可能有点棘手,因为有一些规则专门适用Cells于此列类型.此代码应该处理您遇到的问题.

CurrentCellDirtyStateChanged事件在单击单元格时立即提交更改.您CellValueChanged在调用CommitEdit方法时手动引发事件.

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (dataGridView1.CurrentCell == null) return;
    if ((bool)dataGridView1.CurrentCell.Value == true) MessageBox.Show("true");
    if ((bool)dataGridView1.CurrentCell.Value == false) MessageBox.Show("false");
    MessageBox.Show(dataGridView1.CurrentCell.Value.ToString());
}

private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
    if (dataGridView1.IsCurrentCellDirty)
    {
        dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
    }
}
Run Code Online (Sandbox Code Playgroud)

访问此处获取有关使用该服务的更多信息DataGridViewCheckBoxCell.


Ari*_*rie 5

MSDN在这里说CellValueChanged 在单元格失去焦点之前不会触发。

一些解决方案:

DataGridView.CellContentClick

http://codingeverything.blogspot.com/2013/01/firing-datagridview-cellvaluechanged.html