You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#/.NET实现DataGridView复选框单元格实时更新DataTable

解决DataGridView复选框勾选实时同步到DataTable的问题

你的问题根源在于:DataGridView默认只会在单元格失去焦点(比如切换行)时,才会把编辑后的数值同步到绑定的DataTable里。复选框列点击后不会自动触发这个提交动作,所以需要手动强制提交编辑。

直接用CurrentCellDirtyStateChanged事件就能解决,步骤如下:

  1. 给你的dataGridView_color_selection绑定事件
    可以在窗体的Load事件或者构造函数里加这段代码:

    dataGridView_color_selection.CurrentCellDirtyStateChanged += DataGridView_Color_Selection_CurrentCellDirtyStateChanged;
    
  2. 实现事件处理方法
    当复选框单元格状态改变时,立即提交编辑:

    private void DataGridView_Color_Selection_CurrentCellDirtyStateChanged(object sender, EventArgs e)
    {
        var dgv = sender as DataGridView;
        // 判断当前单元格是复选框且状态已变更
        if (dgv != null && dgv.IsCurrentCellDirty && dgv.CurrentCell is DataGridViewCheckBoxCell)
        {
            // 提交编辑,实时同步到DataTable
            dgv.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }
    }
    

这样设置后,你点击复选框的瞬间,对应DataTable里的字段值就会立刻更新,不用再切换行触发。

内容的提问来源于stack exchange,提问作者PetitMargoulin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 18:40:39