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

继承DataGridViewCheckBoxCell无额外实现仍报单元格格式值类型错误

解决“Formatted value of the cell has a wrong type”错误的方案

这个问题的核心原因是:你自定义的CheckBoxCell没有正确初始化TrueValue和FalseValue属性。原生的DataGridViewCheckBoxColumn在构造时会自动把这两个属性设置为bool类型的true和false,并关联好ValueType,但你的自定义子类没有继承这个默认逻辑,导致单元格无法正确解析你传入的bool值,进而触发类型不匹配错误。

修正方案

只需要在你的CheckBoxCell构造函数里显式设置TrueValue和FalseValue为bool类型的对应值即可,同时确保ThreeState和ValueType的一致性:

public class CheckBoxCell : DataGridViewCheckBoxCell
{
    public CheckBoxCell()
    {
        ThreeState = false;
        TrueValue = true;   // 这里要设为bool类型的true,而非数值1
        FalseValue = false; // 同理设为bool类型的false,而非数值0
        ValueType = typeof(bool);
    }
}

补充说明

如果你希望在列层面统一配置,也可以在CheckBoxColumn的构造函数里对CellTemplate的属性进行初始化:

public class CheckBoxColumn : DataGridViewColumn
{
    public CheckBoxColumn()
    {
        CellTemplate = new CheckBoxCell();
        // 也可以在这里直接设置列的默认属性
        this.ValueType = typeof(bool);
        ((CheckBoxCell)CellTemplate).TrueValue = true;
        ((CheckBoxCell)CellTemplate).FalseValue = false;
    }
}

这样修改后,你的自定义列和单元格就能正确处理bool类型的值,和原生DataGridViewCheckBoxColumn的行为保持一致,同时也能为后续的自定义绘制逻辑打下基础。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:42:52