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

标签 c# .net winforms checkbox datagridview

我正在使用这段代码:

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

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

我需要知道复选框列中的值(真或假)。

我需要为此做什么?

最佳答案

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

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

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

访问here有关使用 DataGridViewCheckBoxCell 的更多信息。

关于c# - DataGridView 中的复选框未触发 CellValueChanged 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17275166/

相关文章:

c# - 在 Web API 2 中找不到方法

c# - 是否可以在 Azure 上运行 .Net UWP 类库?

c# - 在循环的任何步骤中更改 Label.Text

c# - 使用C#进行颜色检测

c# - SerializationException 类型 "is not marked as serializable"- 但它是

C# SecureString 问题

.net - 提示输入数据库连接字符串

c# - .NET/Mono 应用程序的 ldd 的等效项

c# - Microsoft Azure Functions Nuget 包阻止 NET 库打包到 Nuget 中

c# - 使用 sql 查询结果填充 datagridview