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

DataGridView加载时设置ReadOnly=true仍可编辑问题求助

解决DataGridView加载时设置单元格ReadOnly不生效的问题

我完全懂你的困扰——点击CheckBox时能正常切换文本单元格的编辑状态,但初始化加载时明明调试显示已经把对应单元格的ReadOnly设为true了,可单元格还是能编辑。这问题大概率是代码执行时机不对导致的。

问题根源

在构造函数里直接调用disableNotCheckedAllergiesDescription()时,DataGridView还没完成数据绑定的收尾工作。当数据绑定彻底完成后,DataGridView会重新渲染所有单元格,这时候你提前设置的ReadOnly属性会被默认状态覆盖,导致设置失效。而点击事件是在数据绑定完成后触发的,所以能正常生效。

解决方案

把初始化禁用单元格的逻辑移到DataGridView.DataBindingComplete事件里,这个事件会在DataGridView完成所有数据绑定操作后触发,此时设置单元格属性才不会被后续渲染覆盖。

步骤1:添加DataBindingComplete事件处理方法

private void dataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    // 在数据绑定完成后执行初始化禁用逻辑
    disableNotCheckedAllergiesDescription();
}

步骤2:在构造函数中注册事件

修改你的构造函数,移除直接调用disableNotCheckedAllergiesDescription()的代码,换成注册事件:

public People(PersistenceManager persistenceManager) 
{
    InitializeComponent();
    // other stuff
    // 注册数据绑定完成事件
    dataGridView.DataBindingComplete += dataGridView_DataBindingComplete;
}

步骤3:确认原有逻辑正确性

确保你的disableNotCheckedAllergiesDescription方法里,person.Allergies的判断是准确的,并且disableCell方法的逻辑和点击事件里的保持一致(你的现有逻辑是没问题的)。

额外优化提示

如果调整后还是有问题,可以在disableCell和enableCell方法里同步设置列的ReadOnly属性,防止列级别的设置覆盖单元格的设置:

private void disableCell(DataGridViewTextBoxCell cell) 
{
    cell.ReadOnly = true;
    // 同步设置列的ReadOnly,避免列设置优先级更高
    cell.OwningColumn.ReadOnly = true;
    // 样式设置保持不变
    cell.Style.BackColor = Color.LightGray;
    cell.Style.ForeColor = Color.DarkGray;
    cell.Style.SelectionBackColor = Color.LightGray;
    cell.Style.SelectionForeColor = Color.DarkGray;
}

private void enableCell(DataGridViewTextBoxCell cell) 
{
    cell.ReadOnly = false;
    cell.OwningColumn.ReadOnly = false;
    // 样式设置保持不变
    cell.Style.BackColor = Color.White;
    cell.Style.ForeColor = Color.Black;
    cell.Style.SelectionBackColor = Color.Blue;
    cell.Style.SelectionForeColor = Color.White;
}

这样调整后,初始化加载时就能正确禁用未勾选CheckBox对应的文本单元格了。

内容的提问来源于stack exchange,提问作者Alvaro Rodriguez Scelza

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:40:07