C#/.NET实现DataGridView复选框单元格实时更新DataTable
解决DataGridView复选框勾选实时同步到DataTable的问题
你的问题根源在于:DataGridView默认只会在单元格失去焦点(比如切换行)时,才会把编辑后的数值同步到绑定的DataTable里。复选框列点击后不会自动触发这个提交动作,所以需要手动强制提交编辑。
直接用CurrentCellDirtyStateChanged事件就能解决,步骤如下:
给你的
dataGridView_color_selection绑定事件
可以在窗体的Load事件或者构造函数里加这段代码:dataGridView_color_selection.CurrentCellDirtyStateChanged += DataGridView_Color_Selection_CurrentCellDirtyStateChanged;实现事件处理方法
当复选框单元格状态改变时,立即提交编辑: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
相关产品推荐
相关产品推荐

